diff --git a/db/changes/10470-family/00-accountingType.sql b/db/changes/10470-family/00-accountingType.sql deleted file mode 100644 index 964027e3a..000000000 --- a/db/changes/10470-family/00-accountingType.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE `vn`.`accountingType` ADD daysInFuture INT NULL; -ALTER TABLE `vn`.`accountingType` MODIFY COLUMN daysInFuture int(11) DEFAULT 0 NULL; -UPDATE `vn`.`accountingType` SET daysInFuture=1 WHERE id=8; \ No newline at end of file diff --git a/db/changes/10470-family/00-aclItemType.sql b/db/changes/10470-family/00-aclItemType.sql deleted file mode 100644 index 836a69dfd..000000000 --- a/db/changes/10470-family/00-aclItemType.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('ItemType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('ItemType', '*', 'WRITE', 'ALLOW', 'ROLE', 'buyer'); \ No newline at end of file diff --git a/db/changes/10470-family/00-aclMdb.sql b/db/changes/10470-family/00-aclMdb.sql deleted file mode 100644 index b02ddc451..000000000 --- a/db/changes/10470-family/00-aclMdb.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE IF NOT EXISTS `vn`.`mdbBranch` ( - `name` VARCHAR(255), - PRIMARY KEY(`name`) -); - -CREATE TABLE IF NOT EXISTS `vn`.`mdbVersion` ( - `app` VARCHAR(255) NOT NULL, - `branchFk` VARCHAR(255) NOT NULL, - `version` INT, - CONSTRAINT `mdbVersion_branchFk` FOREIGN KEY (`branchFk`) REFERENCES `vn`.`mdbBranch` (`name`) ON DELETE CASCADE ON UPDATE CASCADE -); - -INSERT IGNORE INTO `salix`.`ACL` (`id`, `model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES(318, 'MdbVersion', '*', '*', 'ALLOW', 'ROLE', 'developer'); diff --git a/db/changes/10470-family/00-chat.sql b/db/changes/10470-family/00-chat.sql deleted file mode 100644 index d4a8f068a..000000000 --- a/db/changes/10470-family/00-chat.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE `vn`.`chat` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `senderFk` int(10) unsigned DEFAULT NULL, - `recipient` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `dated` date DEFAULT NULL, - `checkUserStatus` tinyint(1) DEFAULT NULL, - `message` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, - `status` tinyint(1) DEFAULT NULL, - `attempts` int(1) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `chat_FK` (`senderFk`), - CONSTRAINT `chat_FK` FOREIGN KEY (`senderFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10470-family/00-creditInsurance.sql b/db/changes/10470-family/00-creditInsurance.sql deleted file mode 100644 index 9d4db470b..000000000 --- a/db/changes/10470-family/00-creditInsurance.sql +++ /dev/null @@ -1,8 +0,0 @@ -ALTER TABLE `vn`.`creditInsurance` ADD creditClassificationFk int(11) NULL; - -UPDATE `vn`.`creditInsurance` AS `destiny` - SET `destiny`.`creditClassificationFk`= (SELECT creditClassification FROM `vn`.`creditInsurance` AS `origin` WHERE `origin`.id = `destiny`.id); - -ALTER TABLE `vn`.`creditInsurance` - ADD CONSTRAINT `creditInsurance_creditClassificationFk` FOREIGN KEY (`creditClassificationFk`) - REFERENCES `vn`.`creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/db/changes/10470-family/00-defaultViewConfig.sql b/db/changes/10470-family/00-defaultViewConfig.sql deleted file mode 100644 index d423599b1..000000000 --- a/db/changes/10470-family/00-defaultViewConfig.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`defaultViewConfig` (tableCode, columns) -VALUES ('clientsDetail', '{"id":true,"phone":true,"city":true,"socialName":true,"salesPersonFk":true,"email":true,"name":false,"fi":false,"credit":false,"creditInsurance":false,"mobile":false,"street":false,"countryFk":false,"provinceFk":false,"postcode":false,"created":false,"businessTypeFk":false,"payMethodFk":false,"sageTaxTypeFk":false,"sageTransactionTypeFk":false,"isActive":false,"isVies":false,"isTaxDataChecked":false,"isEqualizated":false,"isFreezed":false,"hasToInvoice":false,"hasToInvoiceByAddress":false,"isToBeMailed":false,"hasLcr":false,"hasCoreVnl":false,"hasSepaVnl":false}'); - diff --git a/db/changes/10470-family/00-ticket_doRefund.sql b/db/changes/10470-family/00-ticket_doRefund.sql deleted file mode 100644 index f4ecf29d7..000000000 --- a/db/changes/10470-family/00-ticket_doRefund.sql +++ /dev/null @@ -1,127 +0,0 @@ -DROP PROCEDURE IF EXISTS `vn`.`ticket_doRefund`; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_doRefund`(OUT vNewTicket INT) -BEGIN -/** - * Crea un ticket de abono a partir de tmp.sale y/o tmp.ticketService - * - * @return vNewTicket - */ - DECLARE vDone BIT DEFAULT 0; - DECLARE vClientFk MEDIUMINT; - DECLARE vWarehouse TINYINT; - DECLARE vCompany MEDIUMINT; - DECLARE vAddress MEDIUMINT; - DECLARE vRefundAgencyMode INT; - DECLARE vItemFk INT; - DECLARE vQuantity DECIMAL (10,2); - DECLARE vConcept VARCHAR(50); - DECLARE vPrice DECIMAL (10,2); - DECLARE vDiscount TINYINT; - DECLARE vSaleNew INT; - DECLARE vSaleMain INT; - DECLARE vZoneFk INT; - DECLARE vDescription VARCHAR(50); - DECLARE vTaxClassFk INT; - DECLARE vTicketServiceTypeFk INT; - DECLARE vOriginTicket INT; - - DECLARE cSales CURSOR FOR - SELECT s.id, s.itemFk, - s.quantity, s.concept, s.price, s.discount - FROM tmp.sale s; - - DECLARE cTicketServices CURSOR FOR - SELECT ts.description, - ts.quantity, ts.price, ts.taxClassFk, ts.ticketServiceTypeFk - FROM tmp.ticketService ts; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - SELECT sub.ticketFk INTO vOriginTicket - FROM ( - SELECT s.ticketFk - FROM tmp.sale s - UNION ALL - SELECT ts.ticketFk - FROM tmp.ticketService ts - ) sub - LIMIT 1; - - SELECT id INTO vRefundAgencyMode - FROM agencyMode WHERE `name` = 'ABONO'; - - SELECT clientFk, warehouseFk, companyFk, addressFk - INTO vClientFk, vWarehouse, vCompany, vAddress - FROM ticket - WHERE id = vOriginTicket; - - SELECT id INTO vZoneFk - FROM zone WHERE agencyModeFk = vRefundAgencyMode - LIMIT 1; - - INSERT INTO vn.ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - companyFk, - landed, - zoneFk - ) - SELECT - vClientFk, - CURDATE(), - vAddress, - vRefundAgencyMode, - a.nickname, - vWarehouse, - vCompany, - CURDATE(), - vZoneFk - FROM address a - WHERE a.id = vAddress; - - SET vNewTicket = LAST_INSERT_ID(); - - SET vDone := FALSE; - OPEN cSales; - FETCH cSales INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount; - - WHILE NOT vDone DO - - INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount) - VALUES( vNewTicket, vItemFk, vQuantity, vConcept, vPrice, vDiscount ); - - SET vSaleNew = LAST_INSERT_ID(); - - INSERT INTO vn.saleComponent(saleFk,componentFk,`value`) - SELECT vSaleNew,componentFk,`value` - FROM vn.saleComponent - WHERE saleFk = vSaleMain; - - FETCH cSales INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount; - - END WHILE; - CLOSE cSales; - - SET vDone := FALSE; - OPEN cTicketServices; - FETCH cTicketServices INTO vDescription, vQuantity, vPrice, vTaxClassFk, vTicketServiceTypeFk; - - WHILE NOT vDone DO - - INSERT INTO vn.ticketService(description, quantity, price, taxClassFk, ticketFk, ticketServiceTypeFk) - VALUES(vDescription, vQuantity, vPrice, vTaxClassFk, vNewTicket, vTicketServiceTypeFk); - - FETCH cTicketServices INTO vDescription, vQuantity, vPrice, vTaxClassFk, vTicketServiceTypeFk; - - END WHILE; - CLOSE cTicketServices; - - INSERT INTO vn.ticketRefund(refundTicketFk, originalTicketFk) - VALUES(vNewTicket, vOriginTicket); -END$$ -DELIMITER ; diff --git a/db/changes/10470-family/01-creditInsuranceTriggers.sql b/db/changes/10470-family/01-creditInsuranceTriggers.sql deleted file mode 100644 index 53ba3ba11..000000000 --- a/db/changes/10470-family/01-creditInsuranceTriggers.sql +++ /dev/null @@ -1,11 +0,0 @@ -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`creditInsurance_beforeInsert` - BEFORE INSERT ON `creditInsurance` - FOR EACH ROW -BEGIN - IF NEW.creditClassificationFk THEN - SET NEW.creditClassification = NEW.creditClassificationFk; - END IF; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10470-family/01-tableConfig.sql b/db/changes/10470-family/01-tableConfig.sql deleted file mode 100644 index 685981d90..000000000 --- a/db/changes/10470-family/01-tableConfig.sql +++ /dev/null @@ -1 +0,0 @@ -RENAME TABLE `edi`.`fileConfig` to `edi`.`tableConfig`; \ No newline at end of file diff --git a/db/changes/10470-family/02-fileConfig.sql b/db/changes/10470-family/02-fileConfig.sql deleted file mode 100644 index 3109a4616..000000000 --- a/db/changes/10470-family/02-fileConfig.sql +++ /dev/null @@ -1,22 +0,0 @@ -CREATE TABLE `edi`.`fileConfig` -( - name varchar(25) NOT NULL, - checksum text NULL, - keyValue tinyint(1) default true NOT NULL, - constraint fileConfig_pk - primary key (name) -); - -create unique index fileConfig_name_uindex - on `edi`.`fileConfig` (name); - - -INSERT INTO `edi`.`fileConfig` (name, checksum, keyValue) -VALUES ('FEC010104', null, 0); - -INSERT INTO `edi`.`fileConfig` (name, checksum, keyValue) -VALUES ('VBN020101', null, 1); - -INSERT INTO `edi`.`fileConfig` (name, checksum, keyValue) -VALUES ('florecompc2', null, 1); - diff --git a/db/changes/10471-family/00-chat.sql b/db/changes/10471-family/00-chat.sql deleted file mode 100644 index 6f3c9d437..000000000 --- a/db/changes/10471-family/00-chat.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE `vn`.`chat` MODIFY COLUMN message TEXT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL; -ALTER TABLE `vn`.`chat` MODIFY COLUMN dated DATETIME DEFAULT NULL NULL; -ALTER TABLE `vn`.`chat` ADD error TEXT NULL; diff --git a/db/changes/10472-family/00-creditInsurance.sql b/db/changes/10472-family/00-creditInsurance.sql deleted file mode 100644 index 4731cfb2a..000000000 --- a/db/changes/10472-family/00-creditInsurance.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE `vn`.`creditInsurance` - ADD CONSTRAINT `creditInsurance_creditClassificationFk` FOREIGN KEY (`creditClassificationFk`) - REFERENCES `vn`.`creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/db/changes/10480-june/00-ACL.sql b/db/changes/10480-june/00-ACL.sql deleted file mode 100644 index b13e56e21..000000000 --- a/db/changes/10480-june/00-ACL.sql +++ /dev/null @@ -1,21 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES - ('InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'), - ('InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'), - ('InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'), - ('Ticket','refund','WRITE','ALLOW','ROLE','invoicing'), - ('Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'), - ('Ticket','refund','WRITE','ALLOW','ROLE','claimManager'), - ('Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'), - ('Sale','refund','WRITE','ALLOW','ROLE','claimManager'), - ('TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'), - ('ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'), - ('ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'), - ('Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'), - ('Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'); - -DELETE FROM `salix`.`ACL` WHERE id=313; - -UPDATE `salix`.`ACL` - SET principalId='invoicing' - WHERE id=297; \ No newline at end of file diff --git a/db/changes/10480-june/00-aclShelvingLog.sql b/db/changes/10480-june/00-aclShelvingLog.sql deleted file mode 100644 index dc75142d1..000000000 --- a/db/changes/10480-june/00-aclShelvingLog.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES - ('ShelvingLog','*','READ','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/db/changes/10480-june/00-aclZoneExclusionGeos.sql b/db/changes/10480-june/00-aclZoneExclusionGeos.sql deleted file mode 100644 index 4c0f6c991..000000000 --- a/db/changes/10480-june/00-aclZoneExclusionGeos.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO `salix`.`ACL`(`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('ZoneExclusionGeo', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('ZoneExclusionGeo', '*', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss'); \ No newline at end of file diff --git a/db/changes/10480-june/00-albaran_gestdoc.sql b/db/changes/10480-june/00-albaran_gestdoc.sql deleted file mode 100644 index a0ba93bd3..000000000 --- a/db/changes/10480-june/00-albaran_gestdoc.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE `vn2008`.`albaran_gestdoc` DROP FOREIGN KEY fk_albaran_gestdoc_gestdoc1; -ALTER TABLE `vn2008`.`albaran_gestdoc` ADD CONSTRAINT albaran_gestdoc_FK FOREIGN KEY (gestdoc_id) REFERENCES `vn`.`dms`(id) ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/db/changes/10480-june/00-client.sql b/db/changes/10480-june/00-client.sql deleted file mode 100644 index 4a39bbdf9..000000000 --- a/db/changes/10480-june/00-client.sql +++ /dev/null @@ -1,3 +0,0 @@ -alter table `vn`.`client` - add hasIncoterms tinyint(1) default 0 not null comment 'Received incoterms authorization from client'; - diff --git a/db/changes/10480-june/00-deprecations.sql b/db/changes/10480-june/00-deprecations.sql deleted file mode 100644 index 68becd13e..000000000 --- a/db/changes/10480-june/00-deprecations.sql +++ /dev/null @@ -1,13 +0,0 @@ -DROP FUNCTION `account`.`userGetId`; -DROP FUNCTION `account`.`myUserGetName`; -DROP FUNCTION `account`.`myUserGetId`; -DROP FUNCTION `account`.`myUserHasRole`; -DROP FUNCTION `account`.`myUserHasRoleId`; -DROP FUNCTION `account`.`userGetName`; -DROP FUNCTION `account`.`userHasRole`; -DROP FUNCTION `account`.`userHasRoleId`; -DROP PROCEDURE `account`.`myUserLogout`; -DROP PROCEDURE `account`.`userLogin`; -DROP PROCEDURE `account`.`userLoginWithKey`; -DROP PROCEDURE `account`.`userLoginWithName`; -DROP PROCEDURE `account`.`userSetPassword`; \ No newline at end of file diff --git a/db/changes/10480-june/00-item.sql b/db/changes/10480-june/00-item.sql deleted file mode 100644 index a08d3f4c1..000000000 --- a/db/changes/10480-june/00-item.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE `vn`.`item` MODIFY COLUMN description TEXT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL; diff --git a/db/changes/10480-june/00-route.sql b/db/changes/10480-june/00-route.sql deleted file mode 100644 index beb7d5e41..000000000 --- a/db/changes/10480-june/00-route.sql +++ /dev/null @@ -1,10 +0,0 @@ -UPDATE `vn`.`route` r - JOIN(SELECT r.id, wl.workcenterFk - FROM `vn`.`route` r - JOIN `vn`.`routeLog` rl ON rl.originFk = r.id - JOIN `vn`.`workerLabour` wl ON wl.workerFk = rl.userFk - AND r.created BETWEEN wl.started AND IFNULL(wl.ended, r.created) - WHERE r.created BETWEEN '2021-12-01' AND CURDATE() - AND rl.action = 'insert' - )sub ON sub.id = r.id - SET r.commissionWorkCenterFk = sub.workcenterFk; \ No newline at end of file diff --git a/db/changes/10480-june/00-sample.sql b/db/changes/10480-june/00-sample.sql deleted file mode 100644 index 18beb736d..000000000 --- a/db/changes/10480-june/00-sample.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `vn`.`sample` (code, description, isVisible, hasCompany, hasPreview, datepickerEnabled) -VALUES ('incoterms-authorization', 'Autorización de incoterms', 1, 1, 1, 0); \ No newline at end of file diff --git a/db/changes/10480-june/00-shelving.sql b/db/changes/10480-june/00-shelving.sql deleted file mode 100644 index c66d164c4..000000000 --- a/db/changes/10480-june/00-shelving.sql +++ /dev/null @@ -1,18 +0,0 @@ -ALTER TABLE `vn`.`itemShelving` DROP FOREIGN KEY itemShelving_fk2; -ALTER TABLE `vn`.`shelvingLog` DROP FOREIGN KEY shelvingLog_FK_ibfk_1; -ALTER TABLE `vn`.`smartTag` DROP FOREIGN KEY smartTag_shelving_fk; -ALTER TABLE `vn`.`workerShelving` DROP FOREIGN KEY workerShelving_shelving_fk; - -ALTER TABLE `vn`.`shelving` DROP PRIMARY KEY; -ALTER TABLE `vn`.`shelving` ADD id INT auto_increment PRIMARY KEY NULL; -ALTER TABLE `vn`.`shelving` CHANGE id id int(11) auto_increment NOT NULL FIRST; -ALTER TABLE `vn`.`shelving` ADD CONSTRAINT shelving_UN UNIQUE KEY (code); - -ALTER TABLE `vn`.`itemShelving` ADD CONSTRAINT itemShelving_fk2 FOREIGN KEY (shelvingFk) REFERENCES `vn`.`shelving`(code) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE `vn`.`shelvingLog` ADD CONSTRAINT shelvingLog_FK_ibfk_1 FOREIGN KEY (originFk) REFERENCES `vn`.`shelving`(code) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE `vn`.`smartTag` ADD CONSTRAINT smartTag_FK FOREIGN KEY (shelvingFk) REFERENCES `vn`.`shelving`(code) ON DELETE RESTRICT ON UPDATE CASCADE; -ALTER TABLE `vn`.`workerShelving` ADD CONSTRAINT workerShelving_FK_1 FOREIGN KEY (shelvingFk) REFERENCES `vn`.`shelving`(code) ON DELETE RESTRICT ON UPDATE CASCADE; - -ALTER TABLE vn.shelvingLog DROP FOREIGN KEY shelvingLog_FK_ibfk_1; -ALTER TABLE vn.shelvingLog MODIFY COLUMN originFk INT NOT NULL; -ALTER TABLE vn.shelvingLog ADD CONSTRAINT shelvingLog_FK FOREIGN KEY (originFk) REFERENCES vn.shelving(id) ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/db/changes/10480-june/00-ticketRefund_beforeUpsert.sql b/db/changes/10480-june/00-ticketRefund_beforeUpsert.sql deleted file mode 100644 index e6506c5d7..000000000 --- a/db/changes/10480-june/00-ticketRefund_beforeUpsert.sql +++ /dev/null @@ -1,21 +0,0 @@ -DROP PROCEDURE IF EXISTS `vn`.`ticketRefund_beforeUpsert`; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketRefund_beforeUpsert`(vRefundTicketFk INT, vOriginalTicketFk INT) -BEGIN - DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; - - IF vRefundTicketFk = vOriginalTicketFk THEN - CALL util.throw('Original ticket and refund ticket has same id'); - END IF; - - SELECT COUNT(*) INTO vAlreadyExists - FROM ticketRefund - WHERE originalTicketFk = vOriginalTicketFk; - - IF vAlreadyExists > 0 THEN - CALL util.throw('This ticket is already a refund'); - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10480-june/01-claimObservation.sql b/db/changes/10480-june/01-claimObservation.sql deleted file mode 100644 index 8dc126a9e..000000000 --- a/db/changes/10480-june/01-claimObservation.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE `vn`.`claimObservation` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `claimFk` int(10) unsigned NOT NULL, - `workerFk` int(10) unsigned DEFAULT NULL, - `text` text COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `worker_key` (`workerFk`), - KEY `claim_key` (`claimFk`), - KEY `claimObservation_created_IDX` (`created`) USING BTREE, - CONSTRAINT `claimObservation_ibfk_1` FOREIGN KEY (`claimFk`) REFERENCES `vn`.`claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `claimObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE -) COMMENT='Todas las observaciones referentes a una reclamación' \ No newline at end of file diff --git a/db/changes/10480-june/02-claimTextMigration.sql b/db/changes/10480-june/02-claimTextMigration.sql deleted file mode 100644 index fa5f6fe83..000000000 --- a/db/changes/10480-june/02-claimTextMigration.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `vn`.`claimObservation` (`claimFk`, `text`, `created`) -SELECT `id`, `observation`, `created` FROM `vn`.`claim` \ No newline at end of file diff --git a/db/changes/10480-june/04-aclParking.sql b/db/changes/10480-june/04-aclParking.sql deleted file mode 100644 index 05acd68b1..000000000 --- a/db/changes/10480-june/04-aclParking.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('Parking','*','*','ALLOW','ROLE','employee') \ No newline at end of file diff --git a/db/changes/10480-june/04-aclShelving.sql b/db/changes/10480-june/04-aclShelving.sql deleted file mode 100644 index b237dfe0d..000000000 --- a/db/changes/10480-june/04-aclShelving.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('Shelving','*','*','ALLOW','ROLE','employee') \ No newline at end of file diff --git a/db/changes/10481-june/00-aclOsTicket.sql b/db/changes/10481-june/00-aclOsTicket.sql deleted file mode 100644 index ae2a121f5..000000000 --- a/db/changes/10481-june/00-aclOsTicket.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('OsTicket', '*', '*', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/db/changes/10481-june/00-aclOsTicketConfig.sql b/db/changes/10481-june/00-aclOsTicketConfig.sql deleted file mode 100644 index ad53ea6ae..000000000 --- a/db/changes/10481-june/00-aclOsTicketConfig.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('OsTicketConfig', '*', '*', 'ALLOW', 'ROLE', 'it'); \ No newline at end of file diff --git a/db/changes/10481-june/00-osTicketConfig.sql b/db/changes/10481-june/00-osTicketConfig.sql deleted file mode 100644 index 8727c816d..000000000 --- a/db/changes/10481-june/00-osTicketConfig.sql +++ /dev/null @@ -1,16 +0,0 @@ -CREATE TABLE `vn`.`osTicketConfig` ( - `id` int(11) NOT NULL, - `host` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `user` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `password` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `oldStatus` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `newStatusId` int(11) DEFAULT NULL, - `action` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `day` int(11) DEFAULT NULL, - `comment` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `hostDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `userDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `passwordDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `portDb` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; \ No newline at end of file diff --git a/db/changes/10490-august/00-ACL.sql b/db/changes/10490-august/00-ACL.sql deleted file mode 100644 index 2cce197b2..000000000 --- a/db/changes/10490-august/00-ACL.sql +++ /dev/null @@ -1,49 +0,0 @@ -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES - ('ClientConsumptionQueue', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Ticket', 'deliveryNotePdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Ticket', 'deliveryNoteEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Ticket', 'deliveryNoteCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Ticket', 'deliveryNoteCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'clientWelcomeHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'clientWelcomeEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'creditRequestPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'creditRequestHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'creditRequestEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'printerSetupHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'printerSetupEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'sepaCoreEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'letterDebtorPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'letterDebtorStHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'letterDebtorStEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'letterDebtorNdHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'letterDebtorNdEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'clientDebtStatementPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'clientDebtStatementHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'clientDebtStatementEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'incotermsAuthorizationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'incotermsAuthorizationHtml', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'incotermsAuthorizationEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Client', 'consumptionSendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'), - ('InvoiceOut', 'invoiceEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('InvoiceOut', 'exportationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('InvoiceOut', 'sendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'), - ('Ticket', 'invoiceCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Ticket', 'invoiceCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Supplier', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Supplier', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Travel', 'extraCommunityPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Travel', 'extraCommunityEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('Entry', 'entryOrderPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('OsTicket', 'osTicketReportEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'), - ('Item', 'buyerWasteEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'), - ('Claim', 'claimPickupPdf', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Claim', 'claimPickupEmail', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'), - ('Item', 'labelPdf', 'READ', 'ALLOW', 'ROLE', 'employee'); - -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('Sector','*','READ','ALLOW','ROLE','employee'); -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('Sector','*','WRITE','ALLOW','ROLE','employee'); diff --git a/db/changes/10490-august/00-acl_receiptPdf.sql b/db/changes/10490-august/00-acl_receiptPdf.sql deleted file mode 100644 index 42f84b87d..000000000 --- a/db/changes/10490-august/00-acl_receiptPdf.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('Receipt', 'receiptPdf', '*', 'ALLOW', 'ROLE', 'salesAssistant'); diff --git a/db/changes/10490-august/00-clientConsumptionQueue.sql b/db/changes/10490-august/00-clientConsumptionQueue.sql deleted file mode 100644 index 2734d32cc..000000000 --- a/db/changes/10490-august/00-clientConsumptionQueue.sql +++ /dev/null @@ -1,9 +0,0 @@ -create table `vn`.`clientConsumptionQueue` -( - id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, - params json not null, - queued datetime default current_timestamp() not null, - printed datetime null, - status varchar(50) default '' null -) - comment 'Queue for client consumption PDF mailing'; diff --git a/db/changes/10490-august/00-invoiceOutQueue.sql b/db/changes/10490-august/00-invoiceOutQueue.sql deleted file mode 100644 index 52ed4a113..000000000 --- a/db/changes/10490-august/00-invoiceOutQueue.sql +++ /dev/null @@ -1 +0,0 @@ -rename table `vn`.`invoiceOut_queue` to `vn`.`invoiceOutQueue`; diff --git a/db/changes/10490-august/00-itemConfig.sql b/db/changes/10490-august/00-itemConfig.sql deleted file mode 100644 index b148aa094..000000000 --- a/db/changes/10490-august/00-itemConfig.sql +++ /dev/null @@ -1,5 +0,0 @@ -ALTER TABLE `vn`.`itemConfig` - ADD id int null PRIMARY KEY first; - -ALTER TABLE `vn`.`itemConfig` - ADD wasteRecipients VARCHAR(50) NOT NULL comment 'Weekly waste report schedule recipients'; diff --git a/db/changes/10490-august/00-printConfig.sql b/db/changes/10490-august/00-printConfig.sql deleted file mode 100644 index c5af09ac9..000000000 --- a/db/changes/10490-august/00-printConfig.sql +++ /dev/null @@ -1,10 +0,0 @@ -create table `salix`.`printConfig` -( - id int auto_increment, - itRecipient varchar(50) null comment 'IT recipients for report mailing', - incidencesEmail varchar(50) null comment 'CAU destinatary email', - constraint printConfig_pk - primary key (id) -) - comment 'Print service config'; - diff --git a/db/changes/10490-august/00-sale_afterUpdate.sql b/db/changes/10490-august/00-sale_afterUpdate.sql deleted file mode 100644 index 407fb52c9..000000000 --- a/db/changes/10490-august/00-sale_afterUpdate.sql +++ /dev/null @@ -1,100 +0,0 @@ -DROP TRIGGER IF EXISTS vn.sale_afterUpdate; -USE vn; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`sale_afterUpdate` - AFTER UPDATE ON `sale` - FOR EACH ROW -BEGIN - DECLARE vIsToSendMail BOOL; - DECLARE vPickedLines INT; - DECLARE vCollectionFk INT; - DECLARE vUserRole VARCHAR(255); - - IF !(NEW.id <=> OLD.id) - OR !(NEW.ticketFk <=> OLD.ticketFk) - OR !(NEW.itemFk <=> OLD.itemFk) - OR !(NEW.quantity <=> OLD.quantity) - OR !(NEW.created <=> OLD.created) - OR !(NEW.isPicked <=> OLD.isPicked) THEN - CALL stock.log_add('sale', NEW.id, OLD.id); - END IF; - - IF !(NEW.price <=> OLD.price) - OR !(NEW.ticketFk <=> OLD.ticketFk) - OR !(NEW.itemFk <=> OLD.itemFk) - OR !(NEW.quantity <=> OLD.quantity) - OR !(NEW.discount <=> OLD.discount) THEN - CALL ticket_requestRecalc(NEW.ticketFk); - CALL ticket_requestRecalc(OLD.ticketFk); - END IF; - - IF !(OLD.ticketFk <=> NEW.ticketFk) THEN - UPDATE ticketRequest SET ticketFk = NEW.ticketFk - WHERE saleFk = NEW.id; - END IF; - - SELECT account.myUser_getName() INTO vUserRole; - SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole; - - IF !(OLD.quantity <=> NEW.quantity) THEN - SELECT COUNT(*) INTO vIsToSendMail - FROM vncontrol.inter i - JOIN vn.state s ON s.id = i.state_id - WHERE s.code='PACKED' - AND i.Id_Ticket = OLD.ticketFk - AND vUserRole IN ('salesPerson', 'salesTeamBoss') - LIMIT 1; - - IF vIsToSendMail THEN - CALL vn.mail_insert('jefesventas@verdnatura.es', - 'noreply@verdnatura.es', - CONCAT('Ticket ', OLD.ticketFk ,' modificada cantidad tras encajado'), - CONCAT('Ticket ', OLD.ticketFk ,'.
', - 'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity, - ' del artículo ', OLD.itemFk, ' tras estado encajado del ticket.
', - 'Este email se ha generado automáticamente' ) - ); - END IF; - IF (OLD.quantity > NEW.quantity) THEN - INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT NEW.id, cm.id, sc.value - FROM saleComponent sc - JOIN component cd ON cd.id = sc.componentFk - JOIN component cm ON cm.code = 'mana' - WHERE saleFk = NEW.id AND cd.code = 'lastUnitsDiscount' - ON DUPLICATE KEY UPDATE value = sc.value + VALUES(value); - - DELETE sc.* - FROM vn.saleComponent sc - JOIN component c ON c.id = sc.componentFk - WHERE saleFk = NEW.id AND c.code = 'lastUnitsDiscount'; - END IF; - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE - AND s.id = NEW.id - AND r.created >= CURDATE() - GROUP BY r.id; - END IF; - - IF !(ABS(NEW.isPicked) <=> ABS(OLD.isPicked)) AND NEW.quantity > 0 THEN - - UPDATE vn.collection c - JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk - SET c.salePickedCount = c.salePickedCount + IF(NEW.isPicked != 0, 1, -1); - - END IF; - - IF !(NEW.quantity <=> OLD.quantity) AND (NEW.quantity = 0 OR OLD.quantity = 0) THEN - - UPDATE vn.collection c - JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk - SET c.saleTotalCount = c.saleTotalCount + IF(OLD.quantity = 0, 1, -1); - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10490-august/00-sample.sql b/db/changes/10490-august/00-sample.sql deleted file mode 100644 index f84cd723e..000000000 --- a/db/changes/10490-august/00-sample.sql +++ /dev/null @@ -1,6 +0,0 @@ -alter table `vn`.`sample` - add model VARCHAR(25) null comment 'Model name in plural'; - -UPDATE vn.sample t - SET t.model = 'Clients' - WHERE t.id IN(12, 13, 14, 15, 16, 18, 19, 20); \ No newline at end of file diff --git a/db/changes/10490-august/00-user_hasGrant.sql b/db/changes/10490-august/00-user_hasGrant.sql deleted file mode 100644 index 60d1273d8..000000000 --- a/db/changes/10490-august/00-user_hasGrant.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE `account`.`user` ADD hasGrant TINYINT(1) NOT NULL; diff --git a/db/changes/10491-august/00-ACL_workerDisableExcluded.sql b/db/changes/10491-august/00-ACL_workerDisableExcluded.sql deleted file mode 100644 index 2fd9e8b12..000000000 --- a/db/changes/10491-august/00-ACL_workerDisableExcluded.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalId) - VALUES ('WorkerDisableExcluded','*','*','ALLOW','hr'); \ No newline at end of file diff --git a/db/changes/10491-august/00-aclBusiness.sql b/db/changes/10491-august/00-aclBusiness.sql deleted file mode 100644 index 8ea2c6d83..000000000 --- a/db/changes/10491-august/00-aclBusiness.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('Business', '*', '*', 'ALLOW', 'ROLE', 'hr'); \ No newline at end of file diff --git a/db/changes/10491-august/00-aclUsesMana.sql b/db/changes/10491-august/00-aclUsesMana.sql deleted file mode 100644 index 5bb7178dd..000000000 --- a/db/changes/10491-august/00-aclUsesMana.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('Sale', 'usesMana', '*', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/db/changes/10491-august/00-defaultPayDem_sameAs_production.sql b/db/changes/10491-august/00-defaultPayDem_sameAs_production.sql deleted file mode 100644 index 294247338..000000000 --- a/db/changes/10491-august/00-defaultPayDem_sameAs_production.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `vn`.`payDem` (id,payDem) - VALUES (7,'0'); diff --git a/db/changes/10491-august/00-invoiceInPdf.sql b/db/changes/10491-august/00-invoiceInPdf.sql deleted file mode 100644 index bce256c05..000000000 --- a/db/changes/10491-august/00-invoiceInPdf.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('InvoiceIn', 'invoiceInPdf', 'READ', 'ALLOW', 'ROLE', 'administrative'), - ('InvoiceIn', 'invoiceInEmail', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); diff --git a/db/changes/10491-august/00-newSupplier_ACL.sql b/db/changes/10491-august/00-newSupplier_ACL.sql deleted file mode 100644 index c88f3de3f..000000000 --- a/db/changes/10491-august/00-newSupplier_ACL.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,principalId) - VALUES ('Supplier','newSupplier','WRITE','administrative'); diff --git a/db/changes/10491-august/00-notificationProc.sql b/db/changes/10491-august/00-notificationProc.sql deleted file mode 100644 index 475b2e389..000000000 --- a/db/changes/10491-august/00-notificationProc.sql +++ /dev/null @@ -1,28 +0,0 @@ -DROP FUNCTION IF EXISTS `util`.`notification_send`; -DELIMITER $$ -CREATE DEFINER=`root`@`localhost` FUNCTION `util`.`notification_send`(vNotificationName VARCHAR(255), vParams TEXT, vAuthorFk INT) - RETURNS INT - MODIFIES SQL DATA -BEGIN -/** - * Sends a notification. - * - * @param vNotificationName The notification name - * @param vParams The notification parameters formatted as JSON - * @param vAuthorFk The notification author or %NULL if there is no author - * @return The notification id - */ - DECLARE vNotificationFk INT; - - SELECT id INTO vNotificationFk - FROM `notification` - WHERE `name` = vNotificationName; - - INSERT INTO notificationQueue - SET notificationFk = vNotificationFk, - params = vParams, - authorFk = vAuthorFk; - - RETURN LAST_INSERT_ID(); -END$$ -DELIMITER ; diff --git a/db/changes/10491-august/00-notificationTables.sql b/db/changes/10491-august/00-notificationTables.sql deleted file mode 100644 index 2db7d9874..000000000 --- a/db/changes/10491-august/00-notificationTables.sql +++ /dev/null @@ -1,63 +0,0 @@ -USE util; - -CREATE TABLE notification( - id INT PRIMARY KEY, - `name` VARCHAR(255) UNIQUE, - `description` VARCHAR(255) -); - -CREATE TABLE notificationAcl( - notificationFk INT, - roleFk INT(10) unsigned, - PRIMARY KEY(notificationFk, roleFk) -); - -ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE; - -ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_ibfk_2` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role`(`id`) - ON DELETE RESTRICT - ON UPDATE CASCADE; - -CREATE TABLE notificationSubscription( - notificationFk INT, - userFk INT(10) unsigned, - PRIMARY KEY(notificationFk, userFk) -); - -ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE; - -ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user`(`id`) - ON DELETE CASCADE - ON UPDATE CASCADE; - -CREATE TABLE notificationQueue( - id INT PRIMARY KEY AUTO_INCREMENT, - notificationFk VARCHAR(255), - params JSON, - authorFk INT(10) unsigned NULL, - `status` ENUM('pending', 'sent', 'error') NOT NULL DEFAULT 'pending', - created DATETIME DEFAULT CURRENT_TIMESTAMP, - INDEX(notificationFk), - INDEX(authorFk), - INDEX(status) -); - -ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `nnotificationQueue_ibfk_1` FOREIGN KEY (`notificationFk`) REFERENCES `util`.`notification` (`name`) - ON DELETE CASCADE - ON UPDATE CASCADE; - -ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `notificationQueue_ibfk_2` FOREIGN KEY (`authorFk`) REFERENCES `account`.`user`(`id`) - ON DELETE CASCADE - ON UPDATE CASCADE; - -CREATE TABLE notificationConfig( - id INT PRIMARY KEY AUTO_INCREMENT, - cleanDays MEDIUMINT -); - -INSERT INTO notificationConfig - SET cleanDays = 90; diff --git a/db/changes/10491-august/00-payMethodFk_Allow_Null.sql b/db/changes/10491-august/00-payMethodFk_Allow_Null.sql deleted file mode 100644 index 6d9931d3c..000000000 --- a/db/changes/10491-august/00-payMethodFk_Allow_Null.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE `vn`.`supplier` MODIFY COLUMN payMethodFk tinyint(3) unsigned NULL; \ No newline at end of file diff --git a/db/changes/10491-august/00-supplierActivityFk_Allow_Null.sql b/db/changes/10491-august/00-supplierActivityFk_Allow_Null.sql deleted file mode 100644 index 62aac0556..000000000 --- a/db/changes/10491-august/00-supplierActivityFk_Allow_Null.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE `vn`.`supplier` MODIFY COLUMN supplierActivityFk varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL NULL; \ No newline at end of file diff --git a/db/changes/10491-august/00-ticket_closeByTicket.sql b/db/changes/10491-august/00-ticket_closeByTicket.sql deleted file mode 100644 index f378b1146..000000000 --- a/db/changes/10491-august/00-ticket_closeByTicket.sql +++ /dev/null @@ -1,35 +0,0 @@ -drop procedure `vn`.`ticket_closeByTicket`; - -DELIMITER $$ -$$ -create - definer = `root`@`localhost` procedure `vn`.`ticket_closeByTicket`(IN vTicketFk int) -BEGIN - -/** - * Inserta el ticket en la tabla temporal - * para ser cerrado. - * - * @param vTicketFk Id del ticket - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_close; - CREATE TEMPORARY TABLE tmp.ticket_close ENGINE = MEMORY ( - SELECT - t.id AS ticketFk - FROM ticket t - JOIN agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - JOIN alertLevel al ON al.id = ts.alertLevel - WHERE al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered') - AND t.id = vTicketFk - AND t.refFk IS NULL - GROUP BY t.id); - - CALL ticket_close(); - - DROP TEMPORARY TABLE tmp.ticket_close; -END$$ -DELIMITER ; - - diff --git a/db/changes/10491-august/00-zipConfig.sql b/db/changes/10491-august/00-zipConfig.sql deleted file mode 100644 index 134ce7770..000000000 --- a/db/changes/10491-august/00-zipConfig.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE `vn`.`zipConfig` ( - `id` double(10,2) NOT NULL, - `maxSize` int(11) DEFAULT NULL COMMENT 'in MegaBytes', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; - -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('ZipConfig', '*', '*', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/db/changes/10510-december/00-businessCategory.sql b/db/changes/10510-december/00-businessCategory.sql new file mode 100644 index 000000000..941120062 --- /dev/null +++ b/db/changes/10510-december/00-businessCategory.sql @@ -0,0 +1,31 @@ +CREATE DATABASE IF NOT EXISTS `vn2008`; +CREATE TABLE IF NOT EXISTS `vn2008`.`payroll_categorias` ( + `codcategoria` int(11) NOT NULL, + `descripcion` varchar(255) NOT NULL, + `Tarifa` tinyint(4) NOT NULL, + PRIMARY KEY (`codcategoria`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +CREATE TABLE IF NOT EXISTS `vn`.`businessCategory` ( + `id` int(11) NOT NULL, + `description` varchar(255) NOT NULL, + `rate` tinyint(4) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`businessCategory` (id, description, rate) + SELECT codcategoria, descripcion, Tarifa FROM `vn2008`.`payroll_categorias`; + +ALTER TABLE `vn`.`business` DROP FOREIGN KEY IF EXISTS`business_workerBusinessCategoryFk`; +ALTER TABLE `vn`.`business` ADD CONSTRAINT `business_workerBusinessCategoryFk` FOREIGN KEY (`workerBusinessCategoryFk`) REFERENCES `vn`.`businessCategory` (`id`) ON UPDATE CASCADE; + +DROP TABLE `vn2008`.`payroll_categorias`; + +CREATE OR REPLACE +ALGORITHM = UNDEFINED VIEW `vn2008`.`payroll_categorias` AS +select + `b`.`id` AS `codcategoria`, + `b`.`description` AS `descripcion`, + `b`.`rate` AS `Tarifa` +from + `vn`.`businessCategory` `b`; diff --git a/db/changes/10510-december/deleteMe.keep b/db/changes/10510-december/deleteMe.keep deleted file mode 100644 index 7a4187c02..000000000 --- a/db/changes/10510-december/deleteMe.keep +++ /dev/null @@ -1 +0,0 @@ -Delete this file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 482218ed2..35f6cf35d 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -60,7 +60,7 @@ INSERT INTO `vn`.`educationLevel` (`id`, `name`) INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `userFk`, `bossFk`) SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id, 9 - FROM `vn`.`user`; + FROM `account`.`user`; UPDATE `vn`.`worker` SET bossFk = NULL WHERE id = 20; UPDATE `vn`.`worker` SET bossFk = 20 WHERE id = 1 OR id = 9; @@ -105,20 +105,8 @@ INSERT INTO `account`.`mailForward`(`account`, `forwardTo`) VALUES (1, 'employee@domain.local'); -INSERT INTO `vn`.`printer` (`id`, `name`, `path`, `isLabeler`) - VALUES - (1, 'printer1', 'path1', 0), - (2, 'printer2', 'path2', 1); -INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`, `sectorFk`, `labelerFk`) - VALUES - (1106, 'LGN', 'David Charles', 'Haller', 1106, 19, 432978106, NULL, NULL), - (1107, 'ANT', 'Hank' , 'Pym' , 1107, 19, 432978107, NULL, 1), - (1108, 'DCX', 'Charles' , 'Xavier', 1108, 19, 432978108, 1, NULL), - (1109, 'HLK', 'Bruce' , 'Banner', 1109, 19, 432978109, 1, 2), - (1110, 'JJJ', 'Jessica' , 'Jones' , 1110, 19, 432978110, 2, 1); - INSERT INTO `vn`.`currency`(`id`, `code`, `name`, `ratio`) VALUES (1, 'EUR', 'Euro', 1), @@ -159,6 +147,19 @@ INSERT INTO `vn`.`sector`(`id`, `description`, `warehouseFk`, `isPreviousPrepare (1, 'First sector', 1, 1, 'FIRST'), (2, 'Second sector', 2, 0, 'SECOND'); +INSERT INTO `vn`.`printer` (`id`, `name`, `path`, `isLabeler`, `sectorFk`) + VALUES + (1, 'printer1', 'path1', 0, 1), + (2, 'printer2', 'path2', 1, 1); + +INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`, `sectorFk`, `labelerFk`) + VALUES + (1106, 'LGN', 'David Charles', 'Haller', 1106, 19, 432978106, NULL, NULL), + (1107, 'ANT', 'Hank' , 'Pym' , 1107, 19, 432978107, NULL, NULL), + (1108, 'DCX', 'Charles' , 'Xavier', 1108, 19, 432978108, 1, NULL), + (1109, 'HLK', 'Bruce' , 'Banner', 1109, 19, 432978109, 1, NULL), + (1110, 'JJJ', 'Jessica' , 'Jones' , 1110, 19, 432978110, 2, NULL); + INSERT INTO `vn`.`parking` (`id`, `column`, `row`, `sectorFk`, `code`, `pickingOrder`) VALUES ('1', 700, '01', 1, '700-01', 70001), @@ -216,18 +217,18 @@ INSERT INTO `vn`.`deliveryMethod`(`id`, `code`, `description`) (3, 'PICKUP', 'Recogida'), (4, 'OTHER', 'Otros'); -INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`, `bankFk__`, `warehouseAliasFk`) +INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`, `warehouseAliasFk`) VALUES - (1, 'inhouse pickup' , 1, 1, 1), - (2, 'Super-Man delivery' , 1, 1, 1), - (3, 'Teleportation device' , 1, 1, 1), - (4, 'Entanglement' , 1, 1, 1), - (5, 'Quantum break device' , 1, 1, 1), - (6, 'Walking' , 1, 1, 1), - (7, 'Gotham247' , 1, 1, 1), - (8, 'Gotham247Expensive' , 1, 1, 1), - (9, 'Refund' , 1, 1, 1), - (10, 'Other agency' , 1, 1, 1); + (1, 'inhouse pickup' , 1, 1), + (2, 'Super-Man delivery' , 1, 1), + (3, 'Teleportation device' , 1, 1), + (4, 'Entanglement' , 1, 1), + (5, 'Quantum break device' , 1, 1), + (6, 'Walking' , 1, 1), + (7, 'Gotham247' , 1, 1), + (8, 'Gotham247Expensive' , 1, 1), + (9, 'Refund' , 1, 1), + (10, 'Other agency' , 1, 1); UPDATE `vn`.`agencyMode` SET `id` = 1 WHERE `name` = 'inhouse pickup'; UPDATE `vn`.`agencyMode` SET `id` = 2 WHERE `name` = 'Super-Man delivery'; @@ -1132,11 +1133,11 @@ INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) (32, 36, -92.324), (32, 39, 0.994); -INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `shelve`, `visible`, `grouping`, `packing`, `userFk`) +INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `visible`, `grouping`, `packing`, `userFk`) VALUES - (2, 'GVC', 'A', 1, 1, 1, 1106), - (4, 'HEJ', 'A', 1, 1, 1, 1106), - (1, 'UXN', 'A', 2, 12, 12, 1106); + (2, 'GVC', 1, 1, 1, 1106), + (4, 'HEJ', 1, 1, 1, 1106), + (1, 'UXN', 2, 12, 12, 1106); INSERT INTO `vn`.`itemShelvingSale` (`itemShelvingFk`, `saleFk`, `quantity`, `created`, `userFk`) VALUES @@ -1406,23 +1407,23 @@ INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeF ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Miscellaneous Accessories', 6, 1, '186', '0', '0.0'), ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Adhesives', 7, 1, '277', '0', '0.0'); -INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packageFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`,`producer`,`printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) +INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packageFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) VALUES - (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, NULL, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), - (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, NULL, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), - (3, 3, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 0, NULL, 0.00, 99.6, 99.4, NULL, 0, 1, 0, 1, util.VN_CURDATE()), - (4, 2, 2, 5, 450, 3, 1, 1.000, 1.000, 0.000, 10, 10, 0, NULL, 0.00, 7.30, 7.00, NULL, 0, 1, 0, 2.5, util.VN_CURDATE()), - (5, 3, 3, 55, 500, 5, 1, 1.000, 1.000, 0.000, 1, 1, 0, NULL, 0.00, 78.3, 75.6, NULL, 0, 1, 0, 2.5, util.VN_CURDATE()), - (6, 4, 8, 50, 1000, 4, 1, 1.000, 1.000, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, NULL, 0, 1, 0, 2.5, util.VN_CURDATE()), - (7, 4, 9, 20, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 30.50, 29.00, NULL, 0, 1, 0, 2.5, util.VN_CURDATE()), - (8, 4, 4, 1.25, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, NULL, 0, 1, 0, 2.5, util.VN_CURDATE()), - (9, 4, 4, 1.25, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, NULL, 0, 1, 0, 4, util.VN_CURDATE()), - (10, 5, 1, 50, 10, 4, 1, 2.500, 2.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, NULL, 0, 1, 0, 4, util.VN_CURDATE()), - (11, 5, 4, 1.25, 10, 3, 1, 2.500, 2.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, NULL, 0, 1, 0, 4, util.VN_CURDATE()), - (12, 6, 4, 1.25, 0, 3, 1, 2.500, 2.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, NULL, 0, 1, 0, 4, util.VN_CURDATE()), - (13, 7, 1, 50, 0, 3, 1, 2.000, 2.000, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, NULL, 0, 1, 0, 4, util.VN_CURDATE()), - (14, 7, 2, 5, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 1, NULL, 0.00, 7.30, 7.00, NULL, 0, 1, 0, 4, util.VN_CURDATE()), - (15, 7, 4, 1.25, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, NULL, 0, 1, 0, 4, util.VN_CURDATE()); + (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), + (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), + (3, 3, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 0, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, util.VN_CURDATE()), + (4, 2, 2, 5, 450, 3, 1, 1.000, 1.000, 0.000, 10, 10, 0, NULL, 0.00, 7.30, 7.00, 0, 1, 0, 2.5, util.VN_CURDATE()), + (5, 3, 3, 55, 500, 5, 1, 1.000, 1.000, 0.000, 1, 1, 0, NULL, 0.00, 78.3, 75.6, 0, 1, 0, 2.5, util.VN_CURDATE()), + (6, 4, 8, 50, 1000, 4, 1, 1.000, 1.000, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 2.5, util.VN_CURDATE()), + (7, 4, 9, 20, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 30.50, 29.00, 0, 1, 0, 2.5, util.VN_CURDATE()), + (8, 4, 4, 1.25, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0, 1, 0, 2.5, util.VN_CURDATE()), + (9, 4, 4, 1.25, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()), + (10, 5, 1, 50, 10, 4, 1, 2.500, 2.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 4, util.VN_CURDATE()), + (11, 5, 4, 1.25, 10, 3, 1, 2.500, 2.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()), + (12, 6, 4, 1.25, 0, 3, 1, 2.500, 2.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()), + (13, 7, 1, 50, 0, 3, 1, 2.000, 2.000, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 4, util.VN_CURDATE()), + (14, 7, 2, 5, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 1, NULL, 0.00, 7.30, 7.00, 0, 1, 0, 4, util.VN_CURDATE()), + (15, 7, 4, 1.25, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0, 1, 0, 4, util.VN_CURDATE()); INSERT INTO `hedera`.`order`(`id`, `date_send`, `customer_id`, `delivery_method_id`, `agency_id`, `address_id`, `company_id`, `note`, `source_app`, `confirmed`,`total`, `date_make`, `first_row_stamp`, `confirm_date`) VALUES @@ -1951,30 +1952,34 @@ INSERT INTO `vn`.`workerBusinessType` (`id`, `name`, `isFullTime`, `isPermanent` (100, 'INDEFINIDO A TIEMPO COMPLETO', 1, 1, 1), (109, 'CONVERSION DE TEMPORAL EN INDEFINIDO T.COMPLETO', 1, 1, 1); +INSERT INTO `vn`.`businessCategory` (`id`, `description`, `rate`) + VALUES + (1, 'basic employee', 1); + UPDATE `vn`.`business` b SET `rate` = 7, - `workerBusinessCategoryFk` = 12, + `workerBusinessCategoryFk` = 1, `workerBusinessTypeFk` = 100, `amount` = 900.50 WHERE b.id = 1; UPDATE `vn`.`business` b SET `rate` = 7, - `workerBusinessCategoryFk` = 12, + `workerBusinessCategoryFk` = 1, `workerBusinessTypeFk` = 100, `amount` = 1263.03 WHERE b.id = 1106; UPDATE `vn`.`business` b SET `rate` = 7, - `workerBusinessCategoryFk` = 12, + `workerBusinessCategoryFk` = 1, `workerBusinessTypeFk` = 100, `amount` = 2000 WHERE b.id = 1107; UPDATE `vn`.`business` b SET `rate` = 7, - `workerBusinessCategoryFk` = 12, + `workerBusinessCategoryFk` = 1, `workerBusinessTypeFk` = 100, `amount` = 1500 WHERE b.id = 1108; @@ -2735,4 +2740,9 @@ INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus` INSERT INTO `vn`.`ticketLog` (`id`, `originFk`, `userFk`, `action`, `changedModel`, `oldInstance`, `newInstance`, `changedModelId`) VALUES - (1, 1, 9, 'insert', 'Ticket', '{}', '{"clientFk":1, "nickname": "Bat cave"}', 1); \ No newline at end of file + (1, 1, 9, 'insert', 'Ticket', '{}', '{"clientFk":1, "nickname": "Bat cave"}', 1); + +INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) + VALUES + ('lilium', 'dev', 'http://localhost:8080/#/'), + ('salix', 'dev', 'http://localhost:5000/#!/'); diff --git a/db/dump/structure.sql b/db/dump/structure.sql index cea01d6b1..b8adbddac 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -500,7 +500,7 @@ DELIMITER ;; FOR EACH ROW BEGIN CALL hedera.image_ref('user', NEW.image); - + INSERT IGNORE INTO userSync SET `name` = NEW.`name`; END */;; DELIMITER ; @@ -565,7 +565,7 @@ BEGIN 'jgallego@verdnatura.es', 'Rol modificado', CONCAT( - myUser_getName(), + myUser_getName(), ' ha modificado el rol del usuario ', NEW.`name`, ' de ', OLD.role, ' a ', NEW.role) ); @@ -681,7 +681,7 @@ BEGIN SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); RETURN vSignature = @userSignature; END IF; - + RETURN FALSE; END ;; @@ -710,7 +710,7 @@ BEGIN * @return The user id */ DECLARE vUser INT DEFAULT NULL; - + IF myUser_checkLogin() THEN SET vUser = @userId; @@ -718,7 +718,7 @@ BEGIN SELECT id INTO vUser FROM user WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -753,7 +753,7 @@ BEGIN ELSE SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -825,52 +825,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `passwordGenerate`() RETURNS text CHARSET utf8 COLLATE utf8_unicode_ci READS SQL DATA -BEGIN -/** - * Generates a random password that meets the minimum requirements. - * - * @return Generated password - */ - DECLARE vMinLength TINYINT; - DECLARE vMinAlpha TINYINT; - DECLARE vMinUpper TINYINT; - DECLARE vMinDigits TINYINT; - DECLARE vMinPunct TINYINT; - DECLARE vAlpha TINYINT DEFAULT 0; - DECLARE vUpper TINYINT DEFAULT 0; - DECLARE vDigits TINYINT DEFAULT 0; - DECLARE vPunct TINYINT DEFAULT 0; - DECLARE vRandIndex INT; - DECLARE vPwd TEXT DEFAULT ''; - - DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; - DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - DECLARE vDigitChars TEXT DEFAULT '1234567890'; - DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; - - SELECT length, nAlpha, nUpper, nDigits, nPunct - INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; - - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha - OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO - SET vRandIndex = FLOOR((RAND() * 4) + 1); - - CASE - WHEN vRandIndex = 1 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); - SET vAlpha = vAlpha + 1; - WHEN vRandIndex = 2 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); - SET vUpper = vUpper + 1; - WHEN vRandIndex = 3 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); - SET vDigits = vDigits + 1; - WHEN vRandIndex = 4 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); - SET vPunct = vPunct + 1; - END CASE; - END WHILE; - RETURN vPwd; +BEGIN +/** + * Generates a random password that meets the minimum requirements. + * + * @return Generated password + */ + DECLARE vMinLength TINYINT; + DECLARE vMinAlpha TINYINT; + DECLARE vMinUpper TINYINT; + DECLARE vMinDigits TINYINT; + DECLARE vMinPunct TINYINT; + DECLARE vAlpha TINYINT DEFAULT 0; + DECLARE vUpper TINYINT DEFAULT 0; + DECLARE vDigits TINYINT DEFAULT 0; + DECLARE vPunct TINYINT DEFAULT 0; + DECLARE vRandIndex INT; + DECLARE vPwd TEXT DEFAULT ''; + + DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; + DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + DECLARE vDigitChars TEXT DEFAULT '1234567890'; + DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; + + SELECT length, nAlpha, nUpper, nDigits, nPunct + INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; + + WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha + OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO + SET vRandIndex = FLOOR((RAND() * 4) + 1); + + CASE + WHEN vRandIndex = 1 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); + SET vAlpha = vAlpha + 1; + WHEN vRandIndex = 2 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); + SET vUpper = vUpper + 1; + WHEN vRandIndex = 3 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); + SET vDigits = vDigits + 1; + WHEN vRandIndex = 4 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); + SET vPunct = vPunct + 1; + END CASE; + END WHILE; + RETURN vPwd; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -915,23 +915,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `user_getMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN -/** - * From a username, it returns the associated MySQL wich should be used when - * using external authentication systems. - * - * @param vUserName The user name - * @return The associated MySQL role - */ - DECLARE vRole VARCHAR(255); - - SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole - FROM role r - JOIN user u ON u.role = r.id - JOIN roleConfig c - WHERE u.name = vUserName; - - RETURN vRole; +BEGIN +/** + * From a username, it returns the associated MySQL wich should be used when + * using external authentication systems. + * + * @param vUserName The user name + * @return The associated MySQL role + */ + DECLARE vRole VARCHAR(255); + + SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole + FROM role r + JOIN user u ON u.role = r.id + JOIN roleConfig c + WHERE u.name = vUserName; + + RETURN vRole; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -950,20 +950,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETURNS varchar(30) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN -/** - * Gets user name from it's id. - * - * @param vSelf The user id - * @return The user name - */ - DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user - WHERE id = vSelf; - - RETURN vName; +BEGIN +/** + * Gets user name from it's id. + * + * @param vSelf The user id + * @return The user name + */ + DECLARE vName VARCHAR(30); + + SELECT `name` INTO vName + FROM user + WHERE id = vSelf; + + RETURN vName; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -1034,7 +1034,7 @@ BEGIN JOIN role r ON r.id = rr.inheritsFrom WHERE u.`name` = vUser AND r.id = vRoleId; - + RETURN vHasRole; END ;; DELIMITER ; @@ -1093,7 +1093,7 @@ BEGIN AND password = MD5(vPassword) AND active; - IF vAuthIsOk + IF vAuthIsOk THEN CALL myUser_loginWithName (vUserName); ELSE @@ -1154,7 +1154,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(vUserName VAR BEGIN /** * Logs in using only the user name. This procedure is intended to be executed - * by users with a high level of privileges so that normal users should not have + * by users with a high level of privileges so that normal users should not have * execute permissions on it. * * @param vUserName The user name @@ -1190,7 +1190,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`() BEGIN /** * Logouts the user. - */ + */ SET @userId = NULL; SET @userName = NULL; SET @userSignature = NULL; @@ -1313,9 +1313,9 @@ BEGIN SELECT COUNT(*) > 0 INTO vIsRoot FROM tmp.role t - JOIN role r ON r.id = t.id + JOIN role r ON r.id = t.id WHERE r.`name` = 'root'; - + IF vIsRoot THEN INSERT IGNORE INTO tmp.role (id) SELECT id FROM role; @@ -1998,7 +1998,7 @@ BEGIN SELECT `password` = MD5(vOldPassword), `name` INTO vPasswordOk, vUserName FROM user WHERE id = vSelf; - + IF NOT vPasswordOk THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid password'; @@ -2072,7 +2072,7 @@ BEGIN IF vChr REGEXP '[[:alpha:]]' THEN SET vNAlpha = vNAlpha+1; - + IF vChr REGEXP '[A-Z]' THEN SET vNUpper = vNUpper+1; @@ -2132,7 +2132,7 @@ BEGIN SELECT verificationToken = vVerificationToken, `name` INTO vTokenVerified, vUserName FROM user WHERE id = vSelf; - + IF NOT vTokenVerified THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid verification token'; @@ -2559,7 +2559,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -2585,7 +2585,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -3077,11 +3077,11 @@ BEGIN DECLARE vTramo VARCHAR(20); DECLARE vHour INT; - + SET vHour = HOUR(vDateTime) ; - + SET vTramo = - CASE + CASE WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' END ; @@ -3109,7 +3109,7 @@ BEGIN * Inserta en la tabla bancos_evolution los saldos acumulados de cada banco * * @param vStartingDate Fecha desde la cual se recalculan la tabla bs.bancos_evolution - */ + */ DECLARE vCurrentDate DATE; DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, util.VN_CURDATE()); IF IFNULL(vStartingDate,0) < TIMESTAMPADD(YEAR, -5, util.VN_CURDATE()) THEN @@ -3123,49 +3123,49 @@ BEGIN SELECT vCurrentDate, Id_Banco, deuda FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate); - + WHILE vCurrentDate < vMaxDate DO -- insertar solo el dia de ayer INSERT INTO bs.bancos_evolution(Fecha ,Id_Banco, saldo) - SELECT vCurrentDate, Id_Banco, SUM(saldo) + SELECT vCurrentDate, Id_Banco, SUM(saldo) FROM ( SELECT Id_Banco ,saldo FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior UNION ALL - + SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo FROM vn2008.Cajas c JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND Cajafecha = vCurrentDate AND (Serie = 'MB' OR at2.code = 'fundingLine') GROUP BY Id_Banco - )sub + )sub GROUP BY Id_Banco ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); - + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); END WHILE; - -- Ahora actualizamos la quilla + -- Ahora actualizamos la quilla UPDATE bs.bancos_evolution be JOIN ( SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated - FROM vn.time t + FROM vn.time t JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated) WHERE t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY Id_Banco, t.dated ) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha - SET be.quilla = sub.quilla; + SET be.quilla = sub.quilla; -- pagos futuros no concilidados INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, p.id_banco, - importe - FROM vn.time t + FROM vn.time t join vn2008.pago p ON p.fecha <= t.dated WHERE t.dated BETWEEN util.VN_CURDATE() AND vMaxDate AND p.fecha BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3175,7 +3175,7 @@ BEGIN -- cobros futuros INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, r.Id_Banco, SUM(Entregado) - FROM vn.time t + FROM vn.time t JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated WHERE r.Fechacobro > util.VN_CURDATE() AND r.Fechacobro <= vMaxDate AND t.dated BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3185,10 +3185,10 @@ BEGIN -- saldos de la tabla prevision INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, sp.Id_Banco, SUM(Importe) - FROM vn.time t + FROM vn.time t JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY t.dated, sp.Id_Banco @@ -3202,12 +3202,12 @@ BEGIN -- Deuda UPDATE bs.bancos_evolution be JOIN vn2008.Bancos b using(Id_Banco) - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0) , be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux) WHERE Fecha >= vStartingDate; - -- Liquidez + -- Liquidez update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; -- Disponibilidad update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; @@ -3230,14 +3230,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount + SELECT + workerName, + id, + name, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount FROM ( - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3246,11 +3246,11 @@ BEGIN FROM bs.ventas v INNER JOIN vn.`client` c ON v.Id_Cliente = c.id INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) GROUP BY w.id, v.Id_Cliente) UNION ALL - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3284,21 +3284,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en @bs.carteras. - */ - DELETE FROM bs.carteras - WHERE Año >= YEAR(util.VN_CURDATE()) - 1; - - INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) - SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso - FROM vn.time t - JOIN bs.ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 - GROUP BY w.code, t.year , t.month; +BEGIN +/** + * Inserta en @bs.carteras. + */ + DELETE FROM bs.carteras + WHERE Año >= YEAR(util.VN_CURDATE()) - 1; + + INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) + SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso + FROM vn.time t + JOIN bs.ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 + GROUP BY w.code, t.year , t.month; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3330,24 +3330,24 @@ BEGIN DELETE FROM bs.clientNewBorn WHERE lastShipped < vOneYearAgo; - + DELETE FROM ventas WHERE fecha < vFourYearsAgo; - + DELETE FROM payMethodClient WHERE dated < vOneYearAgo; DELETE FROM payMethodClientEvolution WHERE dated < vFourYearsAgo; - DELETE FROM bs.salesByclientSalesPerson + DELETE FROM bs.salesByclientSalesPerson WHERE dated < vFourYearsAgo; - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha < vTwoYearAgo; DELETE FROM salesByItemTypeDay - WHERE dated < vThreeYearAgo; + WHERE dated < vThreeYearAgo; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3415,16 +3415,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`() BLOCK1: BEGIN DECLARE vClientFk INT; - DECLARE vShipped DATE; + DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; - DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; - - DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; - SET vDone := FALSE; + DECLARE vDone boolean; + DECLARE cur cursor for + + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; + + DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; + SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; @@ -3436,7 +3436,7 @@ BLOCK1: BEGIN WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null GROUP BY c.id; OPEN cur; - + LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; @@ -3447,37 +3447,37 @@ BLOCK1: BEGIN END IF; BLOCK2: BEGIN - DECLARE vCurrentShipped DATE; - DECLARE vDone2 boolean; + DECLARE vCurrentShipped DATE; + DECLARE vDone2 boolean; DECLARE cur2 CURSOR FOR - SELECT shipped - FROM vn.ticket + SELECT shipped + FROM vn.ticket WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE() ORDER BY shipped DESC; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE; SET vDone2 := FALSE; OPEN cur2; - + SET vPreviousShipped := vShipped; LOOP2: LOOP SET vDone2 := FALSE; FETCH cur2 INTO vCurrentShipped; - + IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vPreviousShipped + UPDATE bs.clientNewBorn + SET firstShipped = vPreviousShipped WHERE clientFk= vClientFk; - + CLOSE cur2; - LEAVE LOOP2; + LEAVE LOOP2; END IF; - + SET vPreviousShipped := vCurrentShipped; IF vDone2 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vCurrentShipped + UPDATE bs.clientNewBorn + SET firstShipped = vCurrentShipped WHERE clientFk= vClientFk; CLOSE cur2; LEAVE LOOP2; @@ -3487,14 +3487,14 @@ BLOCK1: BEGIN END BLOCK2; END LOOP LOOP1; - UPDATE bs.clientNewBorn cnb + UPDATE bs.clientNewBorn cnb LEFT JOIN (SELECT DISTINCT t.clientFk FROM vn.ticket t JOIN vn.productionConfig pc WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk - SET cnd.isRookie = ISNULL(notRookie.clientFk); - + SET cnd.isRookie = ISNULL(notRookie.clientFk); + END BLOCK1 ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3515,16 +3515,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `comercialesCompleto`(IN vWorker INT BEGIN DECLARE vAYearAgoStarted DATE DEFAULT DATE_FORMAT(TIMESTAMPADD(YEAR, - 1, vDate), '%Y-%m-01'); DECLARE vAYearAgoEnded DATE DEFAULT TIMESTAMPADD(YEAR, - 1, LAST_DAY(vDate)); - + CALL vn.worker_GetHierarchy(vWorker); - + INSERT IGNORE INTO tmp.workerHierarchyList (workerFk) SELECT wd2.workerFk FROM vn.workerDepartment wd2 WHERE wd2.workerFk = vWorker; - + -- Falta que en algunos casos solo tenga en cuenta los tipos afectados. - SELECT + SELECT c.Id_Cliente id_cliente, c.calidad, c.Cliente cliente, @@ -3550,7 +3550,7 @@ BEGIN FROM vn2008.Clientes c LEFT JOIN - (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge FROM vn2008.Greuges g JOIN vn.`client` c ON c.id = g.Id_Cliente LEFT JOIN vn.worker w ON c.salesPersonFk = w.id @@ -3572,14 +3572,14 @@ BEGIN WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente LEFT JOIN - (SELECT + (SELECT Id_Cliente, SUM(importe) consumo FROM bs.ventas v INNER JOIN vn2008.Clientes c USING (Id_Cliente) LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente LEFT JOIN @@ -3640,17 +3640,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN v BEGIN /** * Sustituye los registros de "bs.compradores". - * + * * @param vYear: año ventas * @param vWeekFrom: semana desde * @param vWeekTo: semana hasta */ REPLACE bs.compradores - SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision + SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision FROM bs.ventas v JOIN vn.time tm ON tm.dated = v.fecha - JOIN vn.itemType it ON it.id = v.tipo_id - WHERE tm.year = vYear + JOIN vn.itemType it ON it.id = v.tipo_id + WHERE tm.year = vYear AND tm.week BETWEEN vWeekFrom AND vWeekTo AND it.categoryFk != 6 GROUP BY it.workerFk, tm.week; @@ -3676,22 +3676,22 @@ BEGIN DECLARE vYear INT; DECLARE vWeek INT; DECLARE done BOOL DEFAULT FALSE; - + DECLARE rs CURSOR FOR SELECT year, week FROM vn.time - WHERE dated <= util.VN_CURDATE() - AND year = vYear + WHERE dated <= util.VN_CURDATE() + AND year = vYear AND week >= vWeek; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear + + SELECT MAX(año) INTO vYear FROM compradores; - + SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; + FROM compradores + WHERE año = vYear; OPEN rs; @@ -3700,7 +3700,7 @@ BEGIN WHILE NOT done DO CALL compradores_add(vYear, vWeek, vWeek); - + FETCH rs INTO vYear, vWeek; END WHILE; @@ -3708,7 +3708,7 @@ BEGIN CLOSE rs; CALL compradores_evolution_add; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3740,10 +3740,10 @@ DECLARE i INT DEFAULT 1; SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; IF ISNULL(datFEC) THEN - - SELECT min(fecha) INTO datFEC + + SELECT min(fecha) INTO datFEC FROM bs.ventas; - + INSERT INTO bs.compradores_evolution( Id_Trabajador , fecha , importe) @@ -3752,19 +3752,19 @@ SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; JOIN vn2008.Tipos tp using(tipo_id) WHERE fecha = datFEC GROUP BY Id_Trabajador; - + SET datFEC = TIMESTAMPADD(DAY, 1, datFEC); - + END IF; WHILE datFEC < util.VN_CURDATE() DO - - IF i mod 150 = 0 THEN + + IF i mod 150 = 0 THEN SELECT datFEC; END IF; - + SET i = i + 1; - + REPLACE bs.compradores_evolution( Id_Trabajador , fecha , importe) @@ -3772,7 +3772,7 @@ SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; SELECT Id_Trabajador , datFEC as fecha , sum(importe) as importe - + FROM ( @@ -3780,17 +3780,17 @@ SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; , importe FROM bs.compradores_evolution WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior - + UNION ALL - + SELECT Id_Trabajador , importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual FROM bs.ventas v JOIN vn2008.Tipos tp using(tipo_id) WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC)) AND reino_id != 6 - - )sub + + )sub GROUP BY Id_Trabajador; SET datFEC = TIMESTAMPADD(DAY,1,datFEC); @@ -3820,49 +3820,49 @@ BEGIN * Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias */ DECLARE datFEC DATE DEFAULT '2015-01-01'; - - SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) - INTO datFEC + + SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) + INTO datFEC FROM bs.fondo_maniobra; - + WHILE datFEC < util.VN_CURDATE() DO - + IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos... SELECT datFEC; END IF; - + REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos FROM ( SELECT SUM(io.amount) AS Facturas FROM vn.invoiceOut io - JOIN vn.client c ON io.clientFk = c.id + JOIN vn.client c ON io.clientFk = c.id WHERE c.isRelevant - AND io.companyFk <> 1381 + AND io.companyFk <> 1381 AND io.issued BETWEEN '2011-01-01' AND datFEC ) fac JOIN ( SELECT - SUM(r.amountPaid) AS Cobros - FROM vn.receipt r - JOIN vn.client c ON r.clientFk = c.id - WHERE c.isRelevant + FROM vn.receipt r + JOIN vn.client c ON r.clientFk = c.id + WHERE c.isRelevant AND r.companyFk <> 1381 AND r.payed BETWEEN '2011-01-01' AND datFEC ) cob JOIN ( SELECT - SUM(id.amount) AS Recibidas - FROM vn.invoiceIn ii - JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk + FROM vn.invoiceIn ii + JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk WHERE ii.companyFk <> 1381 AND ii.issued BETWEEN '2015-01-01' AND datFEC ) rec JOIN ( SELECT SUM(p.amount) AS Pagos - FROM vn.payment p - WHERE p.companyFk <>1381 + FROM vn.payment p + WHERE p.companyFk <>1381 AND p.received BETWEEN '2015-01-01' AND datFEC ) pag; - + UPDATE bs.fondo_maniobra JOIN ( SELECT AVG(fondo) AS media @@ -3870,7 +3870,7 @@ BEGIN WHERE fecha <= datFEC ) sub SET fondo_medio = media WHERE fecha = datFEC; - + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); END WHILE; @@ -3894,7 +3894,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`() BEGIN -select Id_Cliente, +select Id_Cliente, Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker from ( select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana @@ -3935,40 +3935,40 @@ BEGIN -- Ventas totales del ultimo año UPDATE indicators - SET lastYearSales = + SET lastYearSales = (SELECT SUM(importe + recargo) FROM ventas v JOIN vn2008.empresa e ON e.id = v.empresa_id JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo WHERE fecha BETWEEN oneYearBefore AND vDated AND eg.grupo = 'Verdnatura' - ) + ) WHERE updated = vDated; - + -- Greuge total acumulado UPDATE indicators - SET totalGreuge = + SET totalGreuge = (SELECT SUM(amount) FROM vn.greuge WHERE shipped <= vDated - ) + ) WHERE updated = vDated; -- Tasa de morosidad con respecto a las ventas del último mes UPDATE indicators - SET latePaymentRate = - (SELECT SUM(amount) - FROM bi.defaulters + SET latePaymentRate = + (SELECT SUM(amount) + FROM bi.defaulters WHERE date = vDated AND amount > 0) / - (SELECT SUM(importe + recargo) - FROM ventas + (SELECT SUM(importe + recargo) + FROM ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) WHERE updated = vDated; -- Número de trabajadores activos UPDATE indicators - SET countEmployee = + SET countEmployee = (SELECT CAST(SUM(cl.hours_week) / 40 AS DECIMAL (10, 2)) FROM vn.business b JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk @@ -3987,7 +3987,7 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias UPDATE indicators - SET lastMonthActiveClients = + SET lastMonthActiveClients = (SELECT COUNT(DISTINCT t.clientFk) FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -3996,9 +3996,9 @@ BEGIN -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores UPDATE indicators - SET lastMonthLostClients = + SET lastMonthLostClients = (SELECT COUNT(lm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4015,9 +4015,9 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores UPDATE indicators - SET lastMonthNewClients = + SET lastMonthNewClients = (SELECT COUNT(cm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4043,7 +4043,7 @@ BEGIN -- Cálculo de las ventas agrupado por semanas SELECT week INTO vWeek - FROM vn.time + FROM vn.time WHERE dated = vDated; TRUNCATE salesByWeek; @@ -4057,12 +4057,12 @@ BEGIN -- Indicador Ventas semana actual UPDATE indicators i - JOIN salesByWeek s ON s.week= vWeek + JOIN salesByWeek s ON s.week= vWeek AND s.year = YEAR(vDated) SET i.thisWeekSales = s.sales WHERE updated = vDated; - -- Indicador ventas semana actual en el año pasado + -- Indicador ventas semana actual en el año pasado UPDATE indicators i JOIN salesByWeek s ON s.week = vWeek AND s.year = YEAR(vDated)-1 @@ -4093,15 +4093,15 @@ BEGIN SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') INTO vDated FROM bs.indicators; - + WHILE vDated < util.VN_CURDATE() DO - + CALL indicatorsUpdate(vDated); - + SELECT TIMESTAMPADD(DAY,1,MAX(updated)) INTO vDated FROM bs.indicators; - + END WHILE; END ;; @@ -4126,30 +4126,30 @@ BEGIN TRUNCATE bs.inspeccionSS_2021; INSERT INTO bs.inspeccionSS_2021 - SELECT wbd.businessFk , - w.id, - w.firstName, - w.lastName, - d.name , - wtc.timed , - cl.hours_week , - t.`year` , - t.week , + SELECT wbd.businessFk , + w.id, + w.firstName, + w.lastName, + d.name , + wtc.timed , + cl.hours_week , + t.`year` , + t.week , t.dated , 0 AS orden FROM vn.workerTimeControl wtc JOIN vn.worker w ON w.id = wtc.userFk - JOIN vn.workerBusinessDated wbd ON wbd.workerFk = wtc.userFk + JOIN vn.workerBusinessDated wbd ON wbd.workerFk = wtc.userFk AND wbd.dated = date(wtc.timed) JOIN vn.time t ON t.dated = wbd.dated - JOIN vn.business b ON b.id = wbd.businessFk - JOIN postgresql.calendar_labour_type AS cl ON b.calendarTypeFk = cl.calendar_labour_type_id - JOIN vn.department d ON d.id = b.departmentFk + JOIN vn.business b ON b.id = wbd.businessFk + JOIN postgresql.calendar_labour_type AS cl ON b.calendarTypeFk = cl.calendar_labour_type_id + JOIN vn.department d ON d.id = b.departmentFk JOIN vn.department d2 ON d2.id = d.parentFk AND d2.name = 'PRODUCCION' WHERE wtc.timed BETWEEN '2020-10-01' AND '2021-04-19' AND d.lft BETWEEN d2.lft AND d2.rgt AND lastName NOT LIKE 'FERRER%'; - + SET @orden := 1; SET @id := 0; SET @day := 0; @@ -4158,7 +4158,7 @@ BEGIN SET orden = IF(id = @id AND day(timed) = @day, @orden := @orden + 1, @orden := 1), id = @id := id + (0 * @day := day(timed)) ORDER BY id, timed; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4180,15 +4180,15 @@ BEGIN DECLARE datSTART DATE; DECLARE datEND DATE; - + SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART FROM bs.m3; - + SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE()); - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha >= datSTART; - + INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3, tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) @@ -4231,51 +4231,51 @@ BEGIN DECLARE vManaBankId INT; DECLARE vManaGreugeTypeId INT; - SELECT id INTO vManaId + SELECT id INTO vManaId FROM vn.component WHERE code = 'mana'; - - SELECT id INTO vManaAutoId + + SELECT id INTO vManaAutoId FROM vn.component WHERE code = 'autoMana'; - + SELECT id INTO vClaimManaId FROM vn.component WHERE code = 'manaClaim'; - - SELECT id INTO vManaBankId + + SELECT id INTO vManaBankId FROM vn.bank WHERE code = 'mana'; - - SELECT id INTO vManaGreugeTypeId + + SELECT id INTO vManaGreugeTypeId FROM vn.greugeType WHERE code = 'mana'; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; - + DELETE FROM vn.clientManaCache WHERE dated = vFromDated; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO SELECT timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO + timestampadd(DAY,-90,vFromDated) + INTO vToDated, vForDeleteDated; - + DELETE FROM vn.clientManaCache WHERE dated <= vForDeleteDated; INSERT INTO vn.clientManaCache(clientFk, mana, dated) - SELECT + SELECT Id_Cliente, cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM + vToDated as dated + FROM ( SELECT cs.Id_Cliente, Cantidad * Valor as mana FROM vn2008.Tickets t @@ -4283,20 +4283,20 @@ BEGIN JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId) - AND t.Fecha > vFromDated + AND t.Fecha > vFromDated AND date(t.Fecha) <= vToDated UNION ALL SELECT r.Id_Cliente, - Entregado FROM vn2008.Recibos r WHERE Id_Banco = vManaBankId - AND Fechacobro > vFromDated + AND Fechacobro > vFromDated AND Fechacobro <= vToDated - + UNION ALL SELECT g.Id_Cliente, g.Importe FROM vn2008.Greuges g WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated + AND Fecha > vFromDated AND Fecha <= vToDated UNION ALL SELECT clientFk, mana @@ -4307,7 +4307,7 @@ BEGIN HAVING Id_Cliente; SET vFromDated = vToDated; - + END WHILE; END ;; @@ -4328,7 +4328,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`() BEGIN -/** +/** * Recalcula el valor del campo con el modificador de precio para el componente de maná automático. */ @@ -4340,7 +4340,7 @@ BEGIN GROUP BY workerFk ) lastYearSales USING(workerFk) SET pricesModifierRate = GREATEST(minRate, LEAST(maxRate, ROUND(- amount/lastYearSales.pesoCarteraMensual,3))); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4372,8 +4372,8 @@ BEGIN DECLARE vId INT; DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask + SELECT id, `schema`, `procedure` + FROM nightTask WHERE finished <= util.VN_CURDATE() OR finished IS NULL ORDER BY `order`; @@ -4406,7 +4406,7 @@ BEGIN vError, vErrorCode ); - + IF vError IS NOT NULL THEN SET vNErrors = vNErrors + 1; @@ -4476,7 +4476,7 @@ BEGIN vError = MESSAGE_TEXT, vErrorCode = RETURNED_SQLSTATE; - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); + CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4495,22 +4495,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`() BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) + INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) SELECT util.VN_CURDATE(), c.payMethodFk, c.id - FROM vn.client c + FROM vn.client c JOIN vn.payMethod p ON c.payMethodFk = p.id; - + TRUNCATE `bs`.`payMethodClientEvolution` ; - + INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) - SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) + SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) FROM bs.payMethodClient p - JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente + JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente FROM bs.ventas v WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk JOIN vn.payMethod pm ON p.payMethodFk = pm.id - GROUP BY dated,payMethodFk; + GROUP BY dated,payMethodFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4530,12 +4530,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE, IN vToDate DATE, IN vProducerFk INT) BEGIN - + DECLARE vFromDateLastYear DATE; DECLARE vToDateLastYear DATE; DECLARE vFromDateTwoYearsAgo DATE; DECLARE vToDateTwoYearsAgo DATE; - + SET vItemFk = IFNULL(vItemFk,0); SET vTypeFk = IFNULL(vTypeFk, 0); SET vCategoryFk = IFNULL(vCategoryFk,0); @@ -4550,19 +4550,19 @@ BEGIN SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha FROM bs.ventas v - JOIN vn.sale s ON s.id = v.Id_Movimiento - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.sale s ON s.id = v.Id_Movimiento + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE vItemFk IN (i.id, 0) AND vTypeFk IN (i.typeFk, 0) AND vCategoryFk IN (it.categoryFk, 0) AND vProducerFk IN (i.producerFk, 0) AND (v.fecha BETWEEN vFromDate AND vToDate OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear - OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo + OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo ); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4581,21 +4581,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) BEGIN - DELETE FROM bs.salePersonEvolution + DELETE FROM bs.salePersonEvolution WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR); - - + + INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - SELECT fecha dated, - CAST(SUM(importe) AS DECIMAL(10,2) ) amount, + SELECT fecha dated, + CAST(SUM(importe) AS DECIMAL(10,2) ) amount, CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , IFNULL(salesPersonFk,0) salesPersonFk FROM bs.ventas v - JOIN vn.client c ON v.Id_Cliente = c.id + JOIN vn.client c ON v.Id_Cliente = c.id JOIN vn.company co ON co.id = v.empresa_id WHERE co.code = "VNL" AND fecha >= vDateStart GROUP BY v.fecha,c.salesPersonFk - ORDER BY salesPersonFk,dated ASC; + ORDER BY salesPersonFk,dated ASC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4617,7 +4617,7 @@ BEGIN /** * Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo - * + * * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer */ @@ -4625,17 +4625,17 @@ BEGIN SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH; END IF; - UPDATE salesByclientSalesPerson + UPDATE salesByclientSalesPerson SET amount = 0, equalizationTax = 0, amountNewBorn = 0 WHERE dated BETWEEN vDatedFrom AND util.yesterday(); - - INSERT INTO salesByclientSalesPerson( - dated, - salesPersonFk, - clientFk, - amount, + + INSERT INTO salesByclientSalesPerson( + dated, + salesPersonFk, + clientFk, + amount, equalizationTax) SELECT s.dated, c.salesPersonFk, @@ -4644,7 +4644,7 @@ BEGIN SUM(s.surcharge) FROM sale s JOIN vn.client c on s.clientFk = c.id - WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() + WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() GROUP BY s.dated, c.salesPersonFk, s.clientFk ON DUPLICATE KEY UPDATE amount= VALUES(amount), equalizationTax= VALUES(equalizationTax); @@ -4676,163 +4676,163 @@ BEGIN /** * Almacena datos relativos a las ventas de artículos agrupados por reino y familia * - * @param vDateStart - * @param vDateEnd + * @param vDateStart + * @param vDateEnd */ - - DELETE FROM bs.salesByItemTypeDay + + DELETE FROM bs.salesByItemTypeDay WHERE dated BETWEEN vDateStart AND vDateEnd; - + INSERT INTO bs.salesByItemTypeDay (itemTypeFk, itemCategoryFk, dated) - SELECT id, categoryFk, dated + SELECT id, categoryFk, dated FROM vn.itemType JOIN vn.`time` WHERE dated BETWEEN vDateStart AND vDateEnd; - + UPDATE bs.salesByItemTypeDay it - JOIN (SELECT ic.id itemCategoryFk, + JOIN (SELECT ic.id itemCategoryFk, it.id itemTypeFk, bs.dated, SUM(bs.amount) netSale FROM bs.sale bs JOIN vn.itemType it ON it.id = bs.typeFk - JOIN vn .itemCategory ic ON ic.id = it.categoryFk + JOIN vn .itemCategory ic ON ic.id = it.categoryFk JOIN vn.client c on c.id = bs.clientFk JOIN vn.sale s ON s.id = bs.saleFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.`time` ti ON ti.dated = bs.dated - WHERE ic.merchandise + WHERE ic.merchandise AND bs.dated BETWEEN vDateStart AND vDateEnd GROUP BY ic.id, it.id, bs.dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk SET it.netSale = sub.netSale; - - + + UPDATE bs.salesByItemTypeDay it - JOIN (SELECT ic.id AS itemCategoryFk, + JOIN (SELECT ic.id AS itemCategoryFk, it.id AS itemTypeFk, bs.dated, SUM(i.stems * s.quantity) stems FROM bs.sale bs JOIN vn.itemType it ON it.id = bs.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.sale s ON s.id = bs.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk JOIN vn.`time` tm ON tm.dated = bs.dated - WHERE ic.merchandise + WHERE ic.merchandise AND bs.dated BETWEEN vDateStart AND vDateEnd - GROUP BY ic.id, it.id, bs.dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk + GROUP BY ic.id, it.id, bs.dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk SET it.stems = sub.stems; - - + + UPDATE bs.salesByItemTypeDay it - JOIN (SELECT ic.id AS itemCategoryFk, + JOIN (SELECT ic.id AS itemCategoryFk, it.id AS itemTypeFk, DATE(t.shipped) dated, COUNT(DISTINCT(i.id)) `references` FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - WHERE ic.merchandise + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk SET it.`references` = sub.`references`; - + UPDATE bs.salesByItemTypeDay it - JOIN (SELECT ic.id AS itemCategoryFk, + JOIN (SELECT ic.id AS itemCategoryFk, it.id AS itemTypeFk, DATE(t.shipped) dated, SUM(i.stems*s.quantity) AS trash FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.client c ON c.id = t.clientFk - WHERE c.name = 'BASURA' + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.client c ON c.id = t.clientFk + WHERE c.name = 'BASURA' AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk - SET it.trash = sub.trash; - + SET it.trash = sub.trash; + UPDATE bs.salesByItemTypeDay it - JOIN (SELECT ic.id AS itemCategoryFk, + JOIN (SELECT ic.id AS itemCategoryFk, it.id AS itemTypeFk, DATE(t.shipped) dated, SUM(IFNULL(i.stems, 1) * s.quantity) AS faults FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.client c ON c.id = t.clientFk - WHERE c.name = 'FALTAS' + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.client c ON c.id = t.clientFk + WHERE c.name = 'FALTAS' AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk - SET it.`faults` = sub.`faults`; - + SET it.`faults` = sub.`faults`; + UPDATE bs.salesByItemTypeDay it - JOIN (SELECT ic.id AS itemCategoryFk, + JOIN (SELECT ic.id AS itemCategoryFk, it.id AS itemTypeFk, DATE(t.shipped) dated, - SUM((cb.quantity * s.price * (100 - s.discount) / 100) * ((cc.maxResponsibility - c.responsibility )/4 )) accepted, + SUM((cb.quantity * s.price * (100 - s.discount) / 100) * ((cc.maxResponsibility - c.responsibility )/4 )) accepted, SUM(cb.quantity * s.price * (100 - s.discount) / 100) claimed FROM vn.claim c JOIN vn.claimBeginning cb ON cb.claimFk = c.id JOIN vn.sale s ON s.id = cb.saleFk JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.claimConfig cc - WHERE ic.merchandise + WHERE ic.merchandise AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) GROUP BY ic.id, it.id, dated) sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk SET it.accepted = sub.accepted, it.claimed = sub.claimed; - + UPDATE bs.salesByItemTypeDay it - JOIN(SELECT itemCategoryFk, - itemTypeFk, - dated, - CAST(SUM(sale) AS DECIMAL(10,2)) sale, + JOIN(SELECT itemCategoryFk, + itemTypeFk, + dated, + CAST(SUM(sale) AS DECIMAL(10,2)) sale, CAST(SUM(buy) AS DECIMAL(10,2))buy - FROM(SELECT ic.id itemCategoryFk, + FROM(SELECT ic.id itemCategoryFk, it.id itemTypeFk, bs.dated, SUM(bs.amount) sale, 0 buy FROM bs.sale bs JOIN vn.itemType it ON it.id = bs.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.client c on c.id = bs.clientFk JOIN vn.`time` tm ON tm.dated = bs.dated JOIN vn.sale s ON s.id = bs.saleFk - JOIN vn.item i ON i.id = s.itemFk - WHERE ic.merchandise + JOIN vn.item i ON i.id = s.itemFk + WHERE ic.merchandise AND bs.dated BETWEEN vDateStart AND vDateEnd GROUP BY ic.id, it.id, bs.dated - UNION ALL - SELECT ic.id, + UNION ALL + SELECT ic.id, it.id, t.landed, 0 , SUM(b.buyingValue * b.quantity) - FROM vn.entry e - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.buy b ON b.entryFk = e.id - 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 + FROM vn.entry e + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.buy b ON b.entryFk = e.id + 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 WHERE ic.merchandise AND t.landed BETWEEN vDateStart AND vDateEnd - GROUP BY ic.id, it.id, t.landed) sub + GROUP BY ic.id, it.id, t.landed) sub GROUP BY itemCategoryFk, itemTypeFk, dated) sub2 ON sub2.dated = it.dated AND sub2.itemCategoryFk = it.itemCategoryFk AND sub2.itemTypeFk = it.itemTypeFk SET it.sale = sub2.sale, it.buy = sub2.buy; - + DROP TEMPORARY TABLE IF EXISTS tmp.`component`; CREATE TEMPORARY TABLE tmp.`component` (PRIMARY KEY (`itemTypeFk`,`dated`), @@ -4840,18 +4840,18 @@ BEGIN KEY `salesByItemTypeDay_dated_idx` (`dated`)) ENGINE = MEMORY SELECT DATE(t.shipped) dated, - ic.id itemCategoryFk, + ic.id itemCategoryFk, it.id itemTypeFk, SUM(s.quantity * IF(c.code = 'purchaseValue', sc.value,0)) costComponent, SUM(s.quantity * IF(ct.isMargin, sc.value,0)) marginComponent FROM vn.ticket t - JOIN vn.sale s ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.saleComponent sc ON sc.saleFk = s.id - STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.sale s ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.saleComponent sc ON sc.saleFk = s.id + STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk WHERE t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) GROUP BY ic.id, it.id, dated; @@ -4860,23 +4860,23 @@ BEGIN SET it.costComponent = c.costComponent, it.marginComponent = c.marginComponent, it.saleComponent = c.costComponent + c.marginComponent; - - DROP TEMPORARY TABLE tmp.`component`; - + + DROP TEMPORARY TABLE tmp.`component`; + /* UPDATE bs.salesByItemTypeDay it JOIN(SELECT DATE(t.shipped) dated, - ic.id itemCategoryFk, + ic.id itemCategoryFk, it.id itemTypeFk, SUM(s.quantity * IF(c.code = 'purchaseValue', sc.value,0)) costComponent, SUM(s.quantity * IF(ct.isMargin, sc.value,0)) marginComponent FROM vn.ticket t - JOIN vn.sale s ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.saleComponent sc ON sc.saleFk = s.id - STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.sale s ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.saleComponent sc ON sc.saleFk = s.id + STRAIGHT_JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk JOIN vn.`time` tm ON tm.dated = DATE(t.shipped) WHERE t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) GROUP BY ic.id, it.id, dated)sub ON sub.dated = it.dated AND sub.itemCategoryFk = it.itemCategoryFk AND sub.itemTypeFk = it.itemTypeFk @@ -4948,13 +4948,13 @@ BEGIN FROM vn.department d JOIN vn.workerDepartment wd ON wd.departmentFk = d.id JOIN account.user u ON u.id = wd.workerFk - JOIN vn.department d2 ON d2.id = d.parentFk + JOIN vn.department d2 ON d2.id = d.parentFk WHERE d2.code = 'VT'; -- VENTA, COMISIÓN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale - ENGINE = MEMORY + ENGINE = MEMORY SELECT YEAR(s.dated) year, MONTH(s.dated) month, u.name, @@ -4964,7 +4964,7 @@ BEGIN cc.minimumSalesByQuarter/3 minimumSalesByMonth FROM bs.salesByclientSalesPerson s - JOIN vn.client c ON c.id = s.salesPersonFk + JOIN vn.client c ON c.id = s.salesPersonFk JOIN account.user u ON u.id = s.salesPersonFk JOIN vn.commissionConfig cc WHERE dated BETWEEN util.firstDayOfMonth(vPreviusMonth) AND LAST_DAY(vPreviusMonth) @@ -4989,8 +4989,8 @@ BEGIN IFNULL(v.portfolioWeight,0) AS walletWeigth FROM bs.vendedores v JOIN account.`user` u ON u.id = v.Id_Trabajador - JOIN vn.saleGoal sg ON sg.`year` = YEAR(vPreviusMonth) - AND sg.`month` = MONTH(vPreviusMonth) + JOIN vn.saleGoal sg ON sg.`year` = YEAR(vPreviusMonth) + AND sg.`month` = MONTH(vPreviusMonth) AND v.portfolioWeight BETWEEN sg.walletWeightFrom AND sg.walletWeightTo WHERE v.año = YEAR(vPreviusMonth)-1 AND v.mes = MONTH(vPreviusMonth) GROUP BY u.id @@ -5111,7 +5111,7 @@ BEGIN LEFT JOIN tmp.newClients nc ON nc.workerFk = sp.workerFk ) sub ORDER BY salesPersonName; - + DROP TEMPORARY TABLE tmp.salesPersons, tmp.sale, @@ -5140,41 +5140,41 @@ BEGIN DECLARE vDated DATE; DECLARE vCont INT DEFAULT 1; - SELECT TIMESTAMPADD(DAY,1,MAX(dated)) INTO vDated + SELECT TIMESTAMPADD(DAY,1,MAX(dated)) INTO vDated FROM bs.salesPersonEvolution; IF ISNULL(vDated) THEN - SELECT MIN(dated) INTO vDated + SELECT MIN(dated) INTO vDated FROM salesByclientSalesPerson; - + INSERT INTO bs.salesPersonEvolution( salesPersonFk, dated, amount, equalizationTax, amountNewBorn ) SELECT salesPersonFk, dated, amount, equalizationTax, amountNewBorn - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated GROUP BY salesPersonFk; - + SET vDated = TIMESTAMPADD(DAY, 1, vDated); END IF; - + WHILE vDated < util.VN_CURDATE() DO - + SET vCont = vCont + 1; - + REPLACE bs.salesPersonEvolution( salesPersonFk, dated, amount) - SELECT salesPersonFk, vDated, SUM(amount) + SELECT salesPersonFk, vDated, SUM(amount) FROM(SELECT salesPersonFk, amount - FROM salesPersonEvolution + FROM salesPersonEvolution WHERE dated = TIMESTAMPADD(DAY,-1,vDated) -- amount acumulado día anterior UNION ALL SELECT salesPersonFk, amount * IF(dated < vDated,-1,1) -- suma amount año actual/ resta amount año anterior - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated IN (vDated, TIMESTAMPADD(DAY,-365,vDated)) )sub GROUP BY salesPersonFk; - + SET vDated = TIMESTAMPADD(DAY,1,vDated); - + END WHILE; END ;; DELIMITER ; @@ -5197,12 +5197,12 @@ BEGIN /** * Actualiza el campo portfolioWeight que indica el peso de la cartera del comercial * - */ + */ DECLARE vStarted DATE DEFAULT DATE_FORMAT(DATE_ADD(util.VN_CURDATE(), INTERVAL -17 MONTH), '%Y-%m-01'); - + UPDATE vendedores v - JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes - SET v.portfolioWeight = NULL + JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes + SET v.portfolioWeight = NULL WHERE t.dated BETWEEN vStarted AND util.VN_CURDATE(); UPDATE vendedores v @@ -5214,10 +5214,10 @@ BEGIN FROM vn.`time` t STRAIGHT_JOIN bs.ventas v ON t.dated = v.fecha JOIN vn.`client` c ON c.id = v.Id_Cliente - WHERE c.lastSalesPersonFk IS NOT NULL + WHERE c.lastSalesPersonFk IS NOT NULL AND v.fecha BETWEEN vStarted AND util.VN_CURDATE() GROUP BY c.lastSalesPersonFk, t.`year`, t.`month` - ) sub ON sub.lastSalesPersonFk = v.Id_Trabajador AND sub.`year` = v.año AND sub.`month`= v.mes + ) sub ON sub.lastSalesPersonFk = v.Id_Trabajador AND sub.`year` = v.año AND sub.`month`= v.mes SET v.portfolioWeight = sub.importe; END ;; DELIMITER ; @@ -5239,30 +5239,30 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add`(intYEAR INT, vQuart BEGIN DECLARE vCommissionRate DOUBLE; - + SELECT rate INTO vCommissionRate FROM vn.commissionConfig; - + -- vaciar tabla DELETE v.* FROM vendedores v JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter; - + REPLACE vendedores(Id_Trabajador, año, mes, importe, comision, portfolioWeight) SELECT c.Id_Trabajador , intYEAR , MONTH(v.fecha) intMONTH - , sum(v.importe) - , sum(v.importe) * vCommissionRate - , sum(v.importe) + , sum(v.importe) + , sum(v.importe) * vCommissionRate + , sum(v.importe) FROM ventas v JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente JOIN vn.`time` t on t.dated = v.fecha WHERE c.Id_Trabajador is not null AND t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter GROUP BY c.Id_Trabajador, t.`month`; - + -- Sustitucion cedidas - lended INSERT INTO vendedores (Id_Trabajador, mes, año, importe, comision) SELECT c.salesPersonFk @@ -5278,7 +5278,7 @@ BEGIN GROUP BY c.salesPersonFk, t.`month` ON DUPLICATE KEY UPDATE comision = comision + VALUES(comision), importe = importe + VALUES(importe); - + -- Sustitucion arrendadas - borrowed INSERT INTO vendedores (Id_Trabajador, mes, año, importe, comision) SELECT scd.substituteFk @@ -5295,7 +5295,7 @@ BEGIN ON DUPLICATE KEY UPDATE comision = comision + VALUES(comision), importe = importe + VALUES(importe); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5314,11 +5314,11 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`() BEGIN - + CALL bs.vendedores_add(YEAR(util.VN_CURDATE()),QUARTER(util.VN_CURDATE())); CALL bs.vendedores_evolution_add; CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 15 DAY); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5354,12 +5354,12 @@ Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes FROM bs.vendedores_evolution; WHILE (vYear < vCurYear) OR (vYear = vCurYear AND vMonth < vCurMonth) DO - + SELECT max(dated), TIMESTAMPADD(DAY,-364,max(dated)) INTO vDateTo, vDateFrom FROM vn.time WHERE year = vYear AND month = vMonth; - + REPLACE bs.vendedores_evolution( workerFk , year , month @@ -5368,14 +5368,14 @@ Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes , vYear as year , vMonth as month , sum(v.importe) as sales - FROM bs.ventas v + FROM bs.ventas v JOIN vn.client c on c.id = v.Id_Cliente WHERE v.fecha BETWEEN vDateFrom AND vDateTo AND c.salesPersonFk is not null GROUP BY c.salesPersonFk; SET vMonth = vMonth + 1; - + IF vMonth = 13 THEN SET vMonth = 1; SET vYear = vYear + 1; @@ -5405,7 +5405,7 @@ BEGIN /** * Añade las ventas que se realizaron de hace * una semana hasta hoy -* +* * @param vStarted Fecha de inicio * @param vEnded Fecha de finalizacion * @@ -5413,7 +5413,7 @@ BEGIN DECLARE vStartingDate DATETIME; DECLARE vEndingDate DATETIME; - IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) + IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN CALL util.throw('fechaDemasiadoAntigua'); END IF; @@ -5422,8 +5422,8 @@ BEGIN SET vStartingDate = vStarted ; SET vEndingDate = vn2008.dayend(vStartingDate); - DELETE - FROM sale + DELETE + FROM sale WHERE dated BETWEEN vStartingDate AND vEnded; WHILE vEndingDate <= vEnded DO @@ -5444,28 +5444,28 @@ BEGIN JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.address a ON a.id = t.addressFk + JOIN vn.address a ON a.id = t.addressFk JOIN vn.client cl ON cl.id = a.clientFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND s.quantity <> 0 AND s.discount <> 100 - AND ic.merchandise + AND ic.merchandise GROUP BY sc.saleFk HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; UPDATE sale s JOIN ( - SELECT s.id, + SELECT s.id, SUM(s.quantity * sc.value ) margen, s.quantity * s.price * (100 - s.discount ) / 100 pvp FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND ct.isMargin = TRUE - GROUP BY s.id) sub ON sub.id = s.saleFk + GROUP BY s.id) sub ON sub.id = s.saleFk SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp; SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); @@ -5491,7 +5491,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_add_launcher`() BEGIN - + /** * Añade las ventas que se realizaron de hace * una semana hasta hoy @@ -5517,104 +5517,104 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) -BEGIN - - /** - * Reemplaza las ventas contables del último año. - * Es el origen de datos para el balance de Entradas - * - * @param vYear Año a reemplazar - * @param vMonth Mes a reemplazar - * - **/ - - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - DELETE FROM bs.ventas_contables - WHERE year = vYear - AND month = vMonth; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - - SELECT vYear - , vMonth - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) - , IF( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,IF(e2.empresa_grupo,2,0) - ) as grupo - , tp.reino_id - , a.tipo_id - , t.empresa_id - , 7000000000 - + IF(e.empresa_grupo = e2.empresa_grupo - ,1 - ,IF(e2.empresa_grupo,2,0) - ) * 1000000 - + tp.reino_id * 10000 as Gasto - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != TIPO_PATRIMONIAL - GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - - INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - SELECT vYear - , vMonth - , sum(ts.quantity * ts.price) - , IF( - c.companyGroupFk = c2.companyGroupFk - ,1 - ,IF(c2.companyGroupFk, 2, 0) - ) as grupo - , NULL - , NULL - , t.companyFk - , 7050000000 - FROM vn.ticketService ts - JOIN vn.ticket t ON ts.ticketFk = t.id - JOIN vn.address a on a.id = t.addressFk - JOIN vn.client cl on cl.id = a.clientFk - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id - JOIN vn.company c on c.id = t.companyFk - LEFT JOIN vn.company c2 on c2.clientFk = cl.id - GROUP BY grupo, t.companyFk ; - - DROP TEMPORARY TABLE tmp.ticket_list; +BEGIN + + /** + * Reemplaza las ventas contables del último año. + * Es el origen de datos para el balance de Entradas + * + * @param vYear Año a reemplazar + * @param vMonth Mes a reemplazar + * + **/ + + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + DELETE FROM bs.ventas_contables + WHERE year = vYear + AND month = vMonth; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + ENGINE = MEMORY + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + + SELECT vYear + , vMonth + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) + , IF( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,IF(e2.empresa_grupo,2,0) + ) as grupo + , tp.reino_id + , a.tipo_id + , t.empresa_id + , 7000000000 + + IF(e.empresa_grupo = e2.empresa_grupo + ,1 + ,IF(e2.empresa_grupo,2,0) + ) * 1000000 + + tp.reino_id * 10000 as Gasto + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != TIPO_PATRIMONIAL + GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; + + INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + SELECT vYear + , vMonth + , sum(ts.quantity * ts.price) + , IF( + c.companyGroupFk = c2.companyGroupFk + ,1 + ,IF(c2.companyGroupFk, 2, 0) + ) as grupo + , NULL + , NULL + , t.companyFk + , 7050000000 + FROM vn.ticketService ts + JOIN vn.ticket t ON ts.ticketFk = t.id + JOIN vn.address a on a.id = t.addressFk + JOIN vn.client cl on cl.id = a.clientFk + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id + JOIN vn.company c on c.id = t.companyFk + LEFT JOIN vn.company c2 on c2.clientFk = cl.id + GROUP BY grupo, t.companyFk ; + + DROP TEMPORARY TABLE tmp.ticket_list; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5633,13 +5633,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`() BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas * **/ - + CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()))); END ;; @@ -5660,12 +5660,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Muestra las ventas (€) de cada cliente * dependiendo del año */ - + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; CREATE TEMPORARY TABLE tmp.ticket_list @@ -5674,8 +5674,8 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - + AND month(f.Fecha) = vMonth; + SELECT vYear Año, vMonth Mes, t.Id_Cliente, @@ -5685,7 +5685,7 @@ BEGIN IF(e2.empresa_grupo,2,0)) AS grupo, t.empresa_id empresa - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente @@ -5699,9 +5699,9 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != 188 GROUP BY t.Id_Cliente, grupo,t.empresa_id; - + DROP TEMPORARY TABLE tmp.ticket_list; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5720,7 +5720,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`() BEGIN - + /** * Devuelve el número de clientes nuevos y muertos, * dependiendo de la fecha actual. @@ -5731,9 +5731,9 @@ BEGIN SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; - + CREATE TEMPORARY TABLE tmp.VivosMuertos SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto FROM vn2008.Clientes c @@ -5749,10 +5749,10 @@ BEGIN WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; - + UPDATE tmp.VivosMuertos vm JOIN - (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente + (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente FROM vn2008.Facturas f JOIN vn2008.time tm ON tm.date = f.Fecha WHERE Fecha BETWEEN @datSTART AND @datEND @@ -5760,9 +5760,9 @@ BEGIN AND fm.Id_Cliente = vm.Id_Cliente SET Nuevo = 1; - + SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - + UPDATE tmp.VivosMuertos vm JOIN ( SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente @@ -5803,23 +5803,23 @@ BEGIN INTO vWeek, vYear FROM vn.time WHERE dated = util.VN_CURDATE(); - + REPLACE bs.waste SELECT *, 100 * mermas / total as porcentaje FROM ( - SELECT buyer, - year, + SELECT buyer, + year, week, family, itemFk, itemTypeFk, - floor(sum(value)) as total, + floor(sum(value)) as total, floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas - FROM vn.saleValue + FROM vn.saleValue where year = vYear and week = vWeek - + GROUP BY family, itemFk - + ) sub ORDER BY mermas DESC; END ;; @@ -5851,56 +5851,56 @@ BEGIN DECLARE vDateEnded DATE; DECLARE vCursor CURSOR FOR - SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) + SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) FROM vn.time t WHERE t.dated BETWEEN vDateStarted AND vDateEnded - GROUP BY year,month; + GROUP BY year,month; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + IF DAY(util.VN_CURDATE()) = 21 THEN - + SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)), LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH)) - INTO vDateStarted, + INTO vDateStarted, vDateEnded; - - DELETE FROM workerLabourDataByMonth + + DELETE FROM workerLabourDataByMonth WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded; OPEN vCursor; l: LOOP SET vDone = FALSE; - + FETCH vCursor INTO vFristDay, vLastDay; - + IF vDone THEN LEAVE l; END IF; - + -- Altas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.workCenter wc ON wc.id = b.workCenterFk JOIN vn.worker w ON w.id = b.workerFk LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk LEFT JOIN (SELECT b.id, b.workerFk FROM vn.business b - LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl + LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk - WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended + WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended )sub ON sub.workerFk = b.workerFk WHERE wc.payrollCenterFk IS NOT NULL AND b.workCenterFk IS NOT NULL AND b.started BETWEEN vFristDay AND vLastDay AND sub.workerFk IS NULL - AND NOT w.isFreelance; + AND NOT w.isFreelance; -- Bajas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5911,12 +5911,12 @@ BEGIN AND b.ended BETWEEN vFristDay AND vLastDay AND wl.started IS NULL AND NOT w.isFreelance; - + -- Anterior al periodo SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY)); - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5926,8 +5926,8 @@ BEGIN AND NOT w.isFreelance; -- Discapacidad - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5961,10 +5961,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `workerProductivity_add`() BEGIN DECLARE vDateFrom DATE; SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 30 DAY) INTO vDateFrom; - - DELETE FROM workerProductivity + + DELETE FROM workerProductivity WHERE dated >= vDateFrom; - + -- SACADORES Y ARTIFICIAL INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, actionFk) SELECT sub.dated, @@ -5978,7 +5978,7 @@ BEGIN DATE(t.shipped) dated, SUM((ic.cm3delivery * s.quantity)/1000000) volume, TIME_TO_SEC(TIMEDIFF( MAX(st.created),MIN(st.created))) + w.minSeconsItemPicker seconds, - a.accion_id + a.accion_id FROM vn.saleTracking st LEFT JOIN vn.salesPreviousPreparated sp ON sp.saleFk = st.saleFk JOIN vn.sale s ON s.id = st.saleFk @@ -5988,70 +5988,70 @@ BEGIN JOIN vncontrol.accion a ON a.accion_id = st.actionFk LEFT JOIN vn.workerDepartment wd ON wd.workerFk = st.workerFk JOIN workerProductivityConfig w ON TRUE - WHERE t.shipped >= vDateFrom - AND ISNULL(sp.saleFk) + WHERE t.shipped >= vDateFrom + AND ISNULL(sp.saleFk) AND (a.accion = 'SACAR' OR a.accion = 'PRESACAR') GROUP BY t.id, t.warehouseFk, st.workerFk ) sub GROUP BY sub.warehouseFk, sub.workerFk, sub.dated; - + -- ENCAJADORES INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, actionFk) SELECT sub2.shipped, sub2.warehouseFk, - sub2.workerFK, - SUM(sub2.volume), + sub2.workerFK, + SUM(sub2.volume), SUM(sub2.seconds), - a.accion_id - FROM (SELECT t.warehouseFk, - SUM(s.volume) volume, - sub.workerFk, + a.accion_id + FROM (SELECT t.warehouseFk, + SUM(s.volume) volume, + sub.workerFk, DATE(t.shipped) shipped, sub.seconds + w.minSeconsPackager seconds, - s.saleFk - FROM vn.saleVolume s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN(SELECT e.workerFk, e.ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(e.created), MIN(e.created))) seconds + s.saleFk + FROM vn.saleVolume s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN(SELECT e.workerFk, e.ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(e.created), MIN(e.created))) seconds FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE e.workerFk IS NOT NULL AND - t.shipped >= vDateFrom + t.shipped >= vDateFrom GROUP BY e.ticketFk )sub ON sub.ticketFk = t.id JOIN workerProductivityConfig w ON TRUE - GROUP BY s.ticketFk, t.warehouseFk + GROUP BY s.ticketFk, t.warehouseFk )sub2 JOIN vncontrol.accion a ON a.accion = 'ENCAJAR' GROUP BY sub2.warehouseFk,sub2.workerFk, sub2.shipped; - + -- REVISADORES INSERT INTO workerProductivity(dated, wareHouseFk, workerFk, volume, seconds, actionFk) SELECT sub2.shipped, sub2.warehouseFk, - sub2.workerFK, - SUM(sub2.volume), + sub2.workerFK, + SUM(sub2.volume), SUM(sub2.seconds), sub2.accion_id - FROM (SELECT t.warehouseFk, - SUM(s.volume) volume, - sub.workerFk, + FROM (SELECT t.warehouseFk, + SUM(s.volume) volume, + sub.workerFk, DATE(t.shipped) shipped, sub.seconds + w.minSeconsPackager seconds, sub.accion_id - FROM vn.saleVolume s + FROM vn.saleVolume s JOIN vn.ticket t ON t.id = s.ticketFk - JOIN(SELECT st.workerFk, t.id ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(st.created), MIN(st.created))) seconds, a.accion_id + JOIN(SELECT st.workerFk, t.id ticketFk,TIME_TO_SEC(TIMEDIFF( MAX(st.created), MIN(st.created))) seconds, a.accion_id FROM vn.saleTracking st JOIN vncontrol.accion a ON a.accion_id = st.actionFk JOIN vn.sale s ON s.id = st.saleFk JOIN vn.ticket t ON s.ticketFk = t.id WHERE a.accion = 'CONTROLAR' - AND t.shipped >= vDateFrom + AND t.shipped >= vDateFrom GROUP BY t.id )sub ON sub.ticketFk = t.id JOIN workerProductivityConfig w ON TRUE - GROUP BY s.ticketFk, t.warehouseFk + GROUP BY s.ticketFk, t.warehouseFk )sub2 GROUP BY sub2.warehouseFk,sub2.workerFk, sub2.shipped; END ;; @@ -6337,7 +6337,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`() BEGIN - REPLACE cache.addressFriendship + REPLACE cache.addressFriendship SELECT addressFk1, addressFk2, count(*) friendship FROM ( @@ -6348,7 +6348,7 @@ BEGIN AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE()) AND t.addressFk != t2.addressFk) sub GROUP BY addressFk1, addressFk2; - + REPLACE cache.zoneAgencyFriendship SELECT r.agencyModeFk, t.zoneFk, count(*) friendship FROM vn.route r @@ -6522,12 +6522,12 @@ BEGIN FROM available a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DELETE a FROM availableNoRaids a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -6706,27 +6706,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = util.VN_NOW(), - cc.expires = LEAST(ADDTIME(util.VN_NOW(), c.lifetime), util.midNight()), - 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 = util.VN_NOW(), + cc.expires = LEAST(ADDTIME(util.VN_NOW(), c.lifetime), util.midNight()), + 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 */ ; @@ -6744,88 +6744,88 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - - DECLARE 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 util.VN_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 util.VN_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 */ ; @@ -6843,24 +6843,24 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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 */ ; @@ -6899,13 +6899,13 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, util.VN_CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, util.VN_CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6952,7 +6952,7 @@ DECLARE rs CURSOR FOR DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; + SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; OPEN rs; @@ -6961,23 +6961,23 @@ DECLARE rs CURSOR FOR WHILE NOT done DO SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - + SET inicioProd = rsDeparture - rsHoras; - + IF inicioProd - resto < myTime THEN - + SET done = TRUE; - + ELSE - + SET departureLimit = rsDeparture; - + FETCH rs INTO rsDeparture, rsHoras , rsInicio; - + -- SELECT rsDeparture, rsHoras , rsInicio; - + END IF; - + END WHILE; SET departureLimit = IFNULL(departureLimit,24); @@ -7022,7 +7022,7 @@ proc: BEGIN DECLARE started DATE; DECLARE ended DATE; DECLARE vLastRefresh DATE; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (vCalc); @@ -7072,14 +7072,14 @@ proc: BEGIN DECLARE datEQ DATETIME; DECLARE timDIF TIME; DECLARE v_calc INT; - + CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id); - + IF !v_refresh THEN LEAVE proc; END IF; - + CALL vn2008.production_control_source(wh_id, 0); DELETE FROM prod_graphic_source; @@ -7097,8 +7097,8 @@ proc: BEGIN WHERE Fecha = util.VN_CURDATE() GROUP BY wh_id, graphCategory ; - - + + CALL cache_calc_end (v_calc); END ;; DELIMITER ; @@ -7119,7 +7119,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `stock_refresh`(v_refresh BOOL) proc: BEGIN /** - * Crea o actualiza la cache con el disponible hasta el día de + * Crea o actualiza la cache con el disponible hasta el día de * ayer. Esta cache es usada como base para otros procedimientos * como el cáculo del visible o del ATP. * @@ -7145,21 +7145,21 @@ proc: BEGIN SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1); SET v_curdate = util.VN_CURDATE(); - + DELETE FROM stock; - + INSERT INTO stock (item_id, warehouse_id, amount) SELECT item_id, warehouse_id, SUM(amount) amount FROM ( - SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount FROM vn.itemTicketOut WHERE shipped >= v_date_inv AND shipped < v_curdate UNION ALL - SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount + SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount FROM vn.itemEntryIn WHERE landed >= v_date_inv AND landed < v_curdate AND isVirtualStock is FALSE UNION ALL - SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount FROM vn.itemEntryOut WHERE shipped >= v_date_inv AND shipped < v_curdate ) t @@ -7189,12 +7189,12 @@ BEGIN (INDEX (id)) ENGINE = MEMORY SELECT id FROM cache_calc; - + DELETE v FROM visible v LEFT JOIN tCalc c ON c.id = v.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -7225,11 +7225,11 @@ proc: BEGIN IF !v_refresh THEN LEAVE proc; END IF; - + -- Calculamos el stock hasta ayer - + CALL `cache`.stock_refresh(false); - + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; CREATE TEMPORARY TABLE vn2008.tmp_item (PRIMARY KEY (item_id)) @@ -7238,9 +7238,9 @@ proc: BEGIN WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_GetVisible(v_warehouse, NULL); + CALL vn.item_GetVisible(v_warehouse, NULL); DELETE FROM visible WHERE calc_id = v_calc; - + INSERT INTO visible (calc_id, item_id,visible) SELECT v_calc, item_id, visible FROM vn2008.tmp_item; @@ -8104,9 +8104,9 @@ DELIMITER ;; BEGIN DECLARE nextID INT; - + SELECT 1 + MAX(id) INTO nextID FROM putOrder ; - + SET NEW.orderTradelineItemID = nextID; END */;; @@ -8128,36 +8128,36 @@ DELIMITER ;; BEFORE UPDATE ON `putOrder` FOR EACH ROW BEGIN - + DECLARE vError VARCHAR(100) DEFAULT 'Orderregel niet meer teruggevonden op basis van de orderps'; DECLARE vVmpIdError INT DEFAULT 7; DECLARE vVmpFk INT; DECLARE vSupplyResponseNumberOfUnits INT; - - SELECT sr.vmpID INTO vVmpFk - FROM edi.supplyResponse sr + + SELECT sr.vmpID INTO vVmpFk + FROM edi.supplyResponse sr WHERE sr.id = NEW.supplyResponseID; - - IF NEW.OrderStatus = 3 - AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) - AND NEW.error = vError - AND vVmpFk = vVmpIdError - - THEN - + + IF NEW.OrderStatus = 3 + AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) + AND NEW.error = vError + AND vVmpFk = vVmpIdError + + THEN + SET NEW.OrderStatus = 2; - + END IF; - + -- Error de disponible menor de lo solicitado IF NEW.error LIKE 'error2602%' THEN - + SELECT NumberOfUnits INTO vSupplyResponseNumberOfUnits - FROM edi.supplyResponse sr + FROM edi.supplyResponse sr WHERE sr.ID = NEW.supplyResponseID; - + SET NEW.error = CONCAT('(',vSupplyResponseNumberOfUnits,') ', NEW.error); - + END IF; END */;; DELIMITER ; @@ -8184,16 +8184,16 @@ BEGIN DECLARE vIsEktSender BOOLEAN; IF NEW.OrderStatus = vOrderStatusDenied AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - + SELECT s.id INTO vSaleFk - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID LIMIT 1; - + UPDATE vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk @@ -8201,7 +8201,7 @@ BEGIN SET s.quantity = 0 WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID; - + INSERT INTO vn.mail (sender, `subject`, body) SELECT IF(u.id IS NOT NULL AND c.email IS NOT NULL, c.email, @@ -8213,26 +8213,26 @@ BEGIN IF (u.id IS NOT NULL AND c.email IS NOT NULL , CONCAT('https://shop.verdnatura.es/#!form=ecomerce%2Fticket&ticket=', t.id ), CONCAT('https://salix.verdnatura.es/#!/ticket/', t.id ,'/summary'))) - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.`client` c ON c.id = t.clientFk LEFT JOIN account.user u ON u.id= c.salesPersonFk AND u.name IN ('ruben', 'ismaelalcolea') WHERE s.id = vSaleFk; - + END IF; IF NEW.OrderStatus = vOrderStatusOK AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - SELECT v.isEktSender INTO vIsEktSender + SELECT v.isEktSender INTO vIsEktSender FROM edi.VMPSettings v - JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID + JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID WHERE sr.id = NEW.supplyResponseID; - + IF NOT vIsEktSender THEN CALL edi.ekt_add(NEW.id); - + END IF; IF NEW.barcode THEN @@ -8241,7 +8241,7 @@ BEGIN SELECT i.id, NEW.barcode FROM vn.item i WHERE i.supplyResponseFk = NEW.supplyResponseID; - + END IF; END IF; @@ -8439,8 +8439,8 @@ BEGIN UPDATE vn.buy b JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk JOIN vn.item i ON i.id = b.itemFk JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits, @@ -8449,7 +8449,7 @@ BEGIN AND am.name = 'LOGIFLORA' AND e.isRaid AND tr.landed >= util.VN_CURDATE(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8590,22 +8590,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - - SET vPictureReference = REPLACE(vPictureReference,'.',''); - - SET vPictureReference = REPLACE(vPictureReference,'/',''); - - SET vPictureReference = REPLACE(vPictureReference,'%',''); - - SET vPictureReference = REPLACE(vPictureReference,':',''); - - SET vPictureReference = REPLACE(vPictureReference,'?',''); - - SET vPictureReference = REPLACE(vPictureReference,'=',''); - - RETURN vPictureReference; - +BEGIN + + SET vPictureReference = REPLACE(vPictureReference,'.',''); + + SET vPictureReference = REPLACE(vPictureReference,'/',''); + + SET vPictureReference = REPLACE(vPictureReference,'%',''); + + SET vPictureReference = REPLACE(vPictureReference,':',''); + + SET vPictureReference = REPLACE(vPictureReference,'?',''); + + SET vPictureReference = REPLACE(vPictureReference,'=',''); + + RETURN vPictureReference; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8629,15 +8629,15 @@ BEGIN DECLARE vOneWeekAgo DATE DEFAULT TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); DELETE FROM ekt WHERE fec < vFourYearsAgo; - + DELETE IGNORE sr.* FROM supplyResponse sr LEFT JOIN edi.deliveryInformation di ON sr.ID = di.supplyResponseID WHERE di.LatestOrderDateTime < vOneWeekAgo OR di.ID IS NULL; - - DELETE FROM putOrder + + DELETE FROM putOrder WHERE created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8655,28 +8655,28 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`() -BEGIN - - DECLARE vID INT; - DECLARE vGap INT DEFAULT 100; - DECLARE vTope INT; - - SELECT MIN(ID), MAX(ID) - INTO vID, vTope - FROM edi.deliveryInformation; - - WHILE vID <= vTope DO - - SET vID = vID + vGap; - - DELETE - FROM edi.deliveryInformation - WHERE ID < vID - AND EarliestDespatchDateTime IS NULL; - - END WHILE; - - +BEGIN + + DECLARE vID INT; + DECLARE vGap INT DEFAULT 100; + DECLARE vTope INT; + + SELECT MIN(ID), MAX(ID) + INTO vID, vTope + FROM edi.deliveryInformation; + + WHILE vID <= vTope DO + + SET vID = vID + vGap; + + DELETE + FROM edi.deliveryInformation + WHERE ID < vID + AND EarliestDespatchDateTime IS NULL; + + END WHILE; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8695,15 +8695,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT) BEGIN - + /** * Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email - * + * * @param vPutOrderFk PutOrderId de donde coger los datos **/ - - INSERT INTO edi.ekt(entryYear, - deliveryNumber, + + INSERT INTO edi.ekt(entryYear, + deliveryNumber, fec, hor, item, @@ -8743,17 +8743,17 @@ BEGIN i.value10 s6, p.id putOrderFk, sr.Item_ArticleCode, - sr.vmpID + sr.vmpID FROM edi.putOrder p - JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID - JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN vn.origin o ON o.id = i.originFk + JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID + JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN vn.origin o ON o.id = i.originFk WHERE p.id = vPutOrderFk; - + CALL edi.ekt_load(LAST_INSERT_ID()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8772,7 +8772,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT) proc:BEGIN - + DECLARE vRef INT; DECLARE vBuy INT; DECLARE vItem INT; @@ -8797,51 +8797,51 @@ proc:BEGIN FROM edi.ekt e LEFT JOIN edi.item i ON e.ref = i.id LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk - LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID + LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id WHERE e.id = vSelf LIMIT 1; - + IF NOT vHasItemGroup THEN - + CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription); - + CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); - + LEAVE proc; - + END IF; - + -- Asigna la entrada SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; - + -- Inserta el cubo si no existe IF vPackage = 800 THEN - + SET vHasToChangePackagingFk = TRUE; - + IF vItem THEN - + SELECT vn.item_getPackage(vItem) INTO vPackage ; - + ELSE - + SET vPackage = 8000 + vQty; INSERT IGNORE INTO vn.packaging(id, width, `depth`) SELECT vPackage, vc.ccLength / vQty, vc.ccWidth FROM vn.volumeConfig vc; - + END IF; - + 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 @@ -8850,27 +8850,27 @@ proc:BEGIN `to` = 'ekt@verdnatura.es'; END IF; END IF; - + -- Si es una compra de Logiflora obtiene el articulo IF vPutOrderFk THEN - + SELECT i.id INTO vItem FROM edi.putOrder po JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID WHERE po.id = vPutOrderFk LIMIT 1; - + END IF; INSERT IGNORE INTO item_track SET item_id = vRef; - + IF IFNULL(vItem,0) = 0 THEN - + -- Intenta obtener el artículo en base a los atributos holandeses - + SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem - FROM edi.ekt e + FROM edi.ekt e JOIN edi.item_track t ON t.item_id = e.ref LEFT JOIN edi.ekt l ON l.ref = e.ref LEFT JOIN vn.buy b ON b.ektFk = l.id @@ -8891,19 +8891,19 @@ proc:BEGIN AND IF(t.pro, l.pro = e.pro, TRUE) AND IF(t.package, l.package = e.package, TRUE) AND IF(t.item, l.item = e.item, TRUE) - AND i.isFloramondo = vIsFloramondoDirect - ORDER BY l.util.VN_NOW DESC, b.id ASC + AND i.isFloramondo = vIsFloramondoDirect + ORDER BY l.util.VN_NOW DESC, b.id ASC LIMIT 1; END IF; - + -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo IF ISNULL(vItem) AND vIsFloramondoDirect THEN - + CALL edi.item_getNewByEkt(vSelf, vItem); - + END IF; - + INSERT INTO vn.buy ( entryFk @@ -8926,15 +8926,15 @@ proc:BEGIN ,e.qty stickers ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing ,IFNULL(b.`grouping`, e.pac) - ,@pac * e.qty + ,@pac * e.qty ,vForceToPacking ,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk) ,(IFNULL(i.weightByPiece,0) * @pac)/1000 - FROM edi.ekt e + FROM edi.ekt e LEFT JOIN vn.buy b ON b.id = vBuy LEFT JOIN vn.item i ON i.id = b.itemFk LEFT JOIN vn.supplier s ON e.pro = s.id - JOIN vn2008.config cfg + JOIN vn2008.config cfg WHERE e.id = vSelf LIMIT 1; @@ -8942,22 +8942,22 @@ proc:BEGIN CREATE TEMPORARY TABLE tmp.buyRecalc SELECT buy.id - FROM vn.buy + FROM vn.buy WHERE ektFk = vSelf; CALL vn.buy_recalcPrices(); -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy IF vPutOrderFk THEN - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT po.saleFk, b.id, account.myUser_getId() FROM edi.putOrder po JOIN vn.buy b ON b.ektFk = vSelf WHERE po.id = vPutOrderFk; - + END IF; - -- Si es una compra directa en Floramondo hay que añadirlo al ticket + -- Si es una compra directa en Floramondo hay que añadirlo al ticket IF vIsFloramondoDirect THEN @@ -8968,7 +8968,7 @@ proc:BEGIN JOIN edi.ekt e ON e.sub = eea.sub AND e.id = vSelf WHERE e.fec = t.shipped LIMIT 1; - + IF ISNULL(vTicketFk) THEN INSERT INTO vn.ticket ( @@ -8996,8 +8996,8 @@ proc:BEGIN z.id, z.price, z.bonus - FROM edi.ekt e - JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + FROM edi.ekt e + JOIN vn.ektEntryAssign eea ON eea.sub = e.sub JOIN vn.address a ON a.id = eea.addressFk JOIN vn.warehouse w ON w.name = 'Floramondo' JOIN vn.company c ON c.code = 'VNL' @@ -9006,11 +9006,11 @@ proc:BEGIN LIMIT 1; SET vTicketFk = LAST_INSERT_ID(); - + INSERT INTO vn.ticketLog - SET originFk = vTicketFk, - userFk = account.myUser_getId(), - `action` = 'insert', + SET originFk = vTicketFk, + userFk = account.myUser_getId(), + `action` = 'insert', description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk); END IF; @@ -9020,9 +9020,9 @@ proc:BEGIN FROM edi.ekt e JOIN edi.floraHollandConfig fhc WHERE e.id = vSelf; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT vSaleFk, b.id, account.myUser_getId() FROM vn.buy b @@ -9033,9 +9033,9 @@ proc:BEGIN FROM edi.ekt e JOIN vn.component c ON c.code = 'purchaseValue' WHERE e.id = vSelf; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin + SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin FROM edi.ekt e JOIN edi.floraHollandConfig fhc JOIN vn.component c ON c.code = 'margin' @@ -9059,38 +9059,38 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_loadNotBuy`() -BEGIN - - /** - * Ejecuta ekt_load para aquellos ekt de hoy que no tienen vn.buy - */ - - DECLARE vEktFk INTEGER; - DECLARE done BOOL; - - - DECLARE cursor1 CURSOR FOR SELECT e.id - FROM edi.ekt e - LEFT JOIN vn.buy b ON b.ektFk = e.id - WHERE e.fec >= util.VN_CURDATE() - AND ISNULL(b.ektFk); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - OPEN cursor1; - bucle: LOOP - - FETCH cursor1 INTO vEktFk; - - IF done THEN - LEAVE bucle; - END IF; - - CALL edi.ekt_load(vEktFk); - - END LOOP bucle; - CLOSE cursor1; - +BEGIN + + /** + * Ejecuta ekt_load para aquellos ekt de hoy que no tienen vn.buy + */ + + DECLARE vEktFk INTEGER; + DECLARE done BOOL; + + + DECLARE cursor1 CURSOR FOR SELECT e.id + FROM edi.ekt e + LEFT JOIN vn.buy b ON b.ektFk = e.id + WHERE e.fec >= util.VN_CURDATE() + AND ISNULL(b.ektFk); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; + + OPEN cursor1; + bucle: LOOP + + FETCH cursor1 INTO vEktFk; + + IF done THEN + LEAVE bucle; + END IF; + + CALL edi.ekt_load(vEktFk); + + END LOOP bucle; + CLOSE cursor1; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9179,7 +9179,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512)) BEGIN /** * Busca transaciones a partir de un código de barras, las marca como escaneadas - * y las devuelve. + * y las devuelve. * Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura * * @param vBarcode Código de compra de una etiqueta de subasta @@ -9218,19 +9218,19 @@ BEGIN ENGINE = MEMORY SELECT id ektFk FROM ekt LIMIT 0; - CASE + CASE WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.cps = vBarcode OR e.batchNumber = vBarcode; WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN INSERT INTO tmp.ekt - SELECT e.id + SELECT e.id FROM edi.ektRecent e - WHERE e.pro = MID(vBarcode,2,6) + WHERE e.pro = MID(vBarcode,2,6) AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5); ELSE @@ -9245,7 +9245,7 @@ BEGIN -- Clásico de subasta -- Trade standard -- Trade que construye como la subasta - -- Trade como el anterior pero sin trade code + -- Trade como el anterior pero sin trade code INSERT INTO tmp.ekt SELECT id FROM ekt @@ -9266,9 +9266,9 @@ BEGIN -- BatchNumber largo IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e - WHERE e.batchNumber + WHERE e.batchNumber = LEFT(vBarcode,vUsefulAuctionLeftSegmentLength) AND e.batchNumber > 0; @@ -9278,7 +9278,7 @@ BEGIN -- Order Number IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.putOrderFk = vBarcode; @@ -9288,7 +9288,7 @@ BEGIN -- deliveryNumber incrustado IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.deliveryNumber = MID(vBarcode, 4, 13) @@ -9299,7 +9299,7 @@ BEGIN END CASE; IF vIsFound THEN - UPDATE ekt e + UPDATE ekt e JOIN tmp.ekt t ON t.ektFk = e.id SET e.scanned = TRUE; END IF; @@ -9345,7 +9345,7 @@ proc: BEGIN ROLLBACK; RESIGNAL; END; - + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN DO RELEASE_LOCK('edi.floramondo_offerRefresh'); @@ -9355,10 +9355,10 @@ proc: BEGIN IF 'test' = (SELECT environment FROM util.config) THEN LEAVE proc; END IF; - + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN LEAVE proc; - END IF; + END IF; SET vStartingTime = util.VN_NOW(); @@ -9863,7 +9863,7 @@ BEGIN /** * Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt - * + * * @param vEktFk Identificador de la tabla edi.ekt */ @@ -9872,17 +9872,17 @@ BEGIN SELECT MIN(id) id INTO vItemFk FROM edi.item_free; - DELETE FROM edi.item_free + DELETE FROM edi.item_free WHERE id = vItemFk; - + COMMIT; - + IF ISNULL(vItemFk) THEN SELECT MAX(i.id) + 1 INTO vItemFk FROM vn.item i; END IF; - + INSERT INTO vn.item(id, @@ -9909,118 +9909,118 @@ BEGIN least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), ifnull(idt.bucket_id, '999')) packageFk, e.cat, TRUE - FROM edi.ekt e - JOIN edi.item i ON i.id = e.`ref` - JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id - LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` + FROM edi.ekt e + JOIN edi.item i ON i.id = e.`ref` + JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id + LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` WHERE e.id = vEktFk; SET @isTriggerDisabled = TRUE; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.item , 1 - FROM edi.ekt e + SELECT vItemFk, t.id , e.item , 1 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Producto' WHERE e.id = vEktFk AND NOT ISNULL(e.item); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.cat , 3 - FROM edi.ekt e + SELECT vItemFk, t.id , e.cat , 3 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Calidad' WHERE e.id = vEktFk AND NOT ISNULL(e.cat); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , s.company_name , 4 - FROM edi.ekt e + SELECT vItemFk, t.id , s.company_name , 4 + FROM edi.ekt e JOIN edi.supplier s ON s.supplier_id = e.pro JOIN vn.tag t ON t.`name` = 'Productor' WHERE e.id = vEktFk AND NOT ISNULL(s.company_name); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s1, 5 + SELECT vItemFk, t.id , e.s1, 5 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 1 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 1 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s1 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s1); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s2, 6 + SELECT vItemFk, t.id , e.s2, 6 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 2 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 2 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s2 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s2); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s3, 7 + SELECT vItemFk, t.id , e.s3, 7 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 3 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 3 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s3 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s3); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s4, 8 + SELECT vItemFk, t.id , e.s4, 8 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 4 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s4 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s4); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s5, 9 + SELECT vItemFk, t.id , e.s5, 9 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 5 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s5 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s5); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s6, 10 + SELECT vItemFk, t.id , e.s6, 10 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 6 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s6 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s6); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 - FROM edi.ekt e + SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = e.`ref` + LEFT JOIN edi.feature f ON f.item_id = e.`ref` LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1' LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value LEFT JOIN vn.itemInk ik ON ik.longName = e.item WHERE e.id = vEktFk - AND ( ink.name IS NOT NULL + AND ( ink.name IS NOT NULL OR ik.color IS NOT NULL) LIMIT 1; @@ -10032,8 +10032,8 @@ BEGIN CALL vn.item_refreshTags(); - SET @isTriggerDisabled = FALSE; - + SET @isTriggerDisabled = FALSE; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10079,7 +10079,7 @@ BEGIN sender = vSender, senderFk = vSenderId, messageId = vMessageId; - + IF vIsDuplicated THEN SELECT id INTO vSelf FROM mail @@ -10104,55 +10104,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_calcCompByFloramondo`(vSelf INT) -BEGIN - - /** - * Recalcula "a pelo" los componentes para un ticket de Floramondo - * - * Pendiente de concretar la solución cuando Logiflora conteste. - * - * @param vSelf Identificador de vn.ticket - */ - - CALL cache.last_buy_refresh(TRUE); - - DELETE sc.* - FROM vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - WHERE s.ticketFk = vSelf; - - UPDATE vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN edi.floraHollandConfig fhc - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' - SET s.price = b.buyingValue * (1 + fhc.floramondoMargin) - WHERE s.ticketFk = vSelf; - - INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT s.id, c.id, MAX(b.buyingValue) - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' - JOIN vn.component c ON c.code = 'purchaseValue' - WHERE s.ticketFk = vSelf - GROUP BY s.id; - - INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT s.id, c.id, MAX(b.buyingValue) * fhc.floramondoMargin - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN edi.floraHollandConfig fhc - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' - JOIN vn.component c ON c.code = 'margin' - WHERE s.ticketFk = vSelf - GROUP BY s.id; - +BEGIN + + /** + * Recalcula "a pelo" los componentes para un ticket de Floramondo + * + * Pendiente de concretar la solución cuando Logiflora conteste. + * + * @param vSelf Identificador de vn.ticket + */ + + CALL cache.last_buy_refresh(TRUE); + + DELETE sc.* + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vSelf; + + UPDATE vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN edi.floraHollandConfig fhc + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' + SET s.price = b.buyingValue * (1 + fhc.floramondoMargin) + WHERE s.ticketFk = vSelf; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT s.id, c.id, MAX(b.buyingValue) + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' + JOIN vn.component c ON c.code = 'purchaseValue' + WHERE s.ticketFk = vSelf + GROUP BY s.id; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT s.id, c.id, MAX(b.buyingValue) * fhc.floramondoMargin + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN edi.floraHollandConfig fhc + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' + JOIN vn.component c ON c.code = 'margin' + WHERE s.ticketFk = vSelf + GROUP BY s.id; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10989,7 +10989,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterInsert` AFTER INSERT ON `order` FOR EACH ROW -BEGIN +BEGIN IF NEW.address_id = 2850 THEN -- Fallo que se insertan no se sabe como tickets en este cliente CALL vn.mail_insert( @@ -10998,7 +10998,7 @@ BEGIN 'Creada order al address 2850', CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) ); - + END IF; END */;; DELIMITER ; @@ -11015,27 +11015,27 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` - AFTER UPDATE ON `order` - FOR EACH ROW -BEGIN - CALL stock.log_add('order', NEW.id, OLD.id); - - IF !(OLD.address_id <=> NEW.address_id) - OR !(OLD.company_id <=> NEW.company_id) - OR !(OLD.customer_id <=> NEW.customer_id) THEN - CALL order_requestRecalc(NEW.id); - END IF; - - IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN - -- Fallo que se actualiza no se sabe como tickets en este cliente - CALL vn.mail_insert( - 'jgallego@verdnatura.es', - 'noreply@verdnatura.es', - 'Actualizada order al address 2850', - CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` + AFTER UPDATE ON `order` + FOR EACH ROW +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; + + IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN + -- Fallo que se actualiza no se sabe como tickets en este cliente + CALL vn.mail_insert( + 'jgallego@verdnatura.es', + 'noreply@verdnatura.es', + 'Actualizada order al address 2850', + CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11150,12 +11150,12 @@ DELIMITER ;; BEGIN DECLARE vIsFirst BOOL; - SELECT (first_row_stamp IS NULL) INTO vIsFirst - FROM `order` + SELECT (first_row_stamp IS NULL) INTO vIsFirst + FROM `order` WHERE id = NEW.orderFk; IF vIsFirst THEN - UPDATE `order` SET first_row_stamp = util.VN_NOW() + UPDATE `order` SET first_row_stamp = util.VN_NOW() WHERE id = NEW.orderFk; END IF; END */;; @@ -11765,7 +11765,7 @@ BEGIN IF vCount = 0 THEN RETURN FALSE; - END IF; + END IF; SELECT COUNT(*) > 0 INTO vHasRole @@ -11846,14 +11846,14 @@ BEGIN * @return tmp.ticketComponent * @return tmp.ticketLot * @return tmp.zoneGetShipped - */ + */ DECLARE vAgencyMode INT; - + SELECT a.agencyModeFk INTO vAgencyMode FROM myClient c JOIN vn.address a ON a.clientFk = c.id - WHERE a.id = vAddress; + WHERE a.id = vAddress; CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); @@ -11866,7 +11866,7 @@ BEGIN JOIN tmp.availableCalc a ON a.calcFk = c.calc_id WHERE c.available > 0 GROUP BY c.item_id; - + CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -11918,7 +11918,7 @@ BEGIN JOIN tmp.availableCalc a ON a.calcFk = c.calc_id WHERE c.available > 0 GROUP BY c.item_id; - + CALL vn.catalog_calculate_beta(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -12020,7 +12020,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vSelf itemFk; CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -12060,7 +12060,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -12069,7 +12069,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); @@ -12078,13 +12078,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -12163,7 +12163,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packageFk @@ -12192,30 +12192,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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 */ ; @@ -12337,7 +12337,7 @@ BEGIN IF vStatus = 'OK' THEN CALL order_checkConfig(vSelf); - + IF vStatus = 'OK' AND vCreated < TIMESTAMPADD(DAY, -1, util.VN_NOW()) THEN CALL order_update(vSelf); @@ -12493,7 +12493,7 @@ BEGIN IF vSelf IS NOT NULL THEN CALL order_confirm(vSelf); - + DELETE FROM basketOrder WHERE orderFk = vSelf; END IF; @@ -12549,9 +12549,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.`order` ENGINE = MEMORY SELECT myBasket_getId() orderFk; - + CALL order_getTax(); - + DROP TEMPORARY TABLE IF EXISTS tmp.`order`; END ;; DELIMITER ; @@ -12580,7 +12580,7 @@ BEGIN SELECT COUNT(*) INTO vIsMine FROM myOrder WHERE id = vSelf; - + IF vIsMine THEN CALL order_addItem(vSelf, vWarehouse, vItem, vAmount); END IF; @@ -12603,11 +12603,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_confirm`(vSelf INT) BEGIN DECLARE vIsMine BOOL; - - SELECT COUNT(*) INTO vIsMine + + SELECT COUNT(*) INTO vIsMine FROM myOrder WHERE id = vSelf; - + IF vIsMine THEN CALL order_confirm(vSelf); END IF; @@ -12640,7 +12640,7 @@ BEGIN SELECT COUNT(*) INTO isMine FROM myOrder WHERE id = vSelf; - + IF isMine THEN CALL order_getAvailable(vSelf); END IF; @@ -12660,62 +12660,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithAddress`( - OUT vSelf INT, - vLandingDate DATE, +CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithAddress`( + OUT vSelf INT, + vLandingDate DATE, vAddressFk INT) -BEGIN -/** - * Crea una nueva orden para el usuario actual especificando - * una fecha de entrega. - * - * @param vSelf Id de la nueva orden - * @param vLandingDate Fecha de entrega - */ - DECLARE vCompany INT; - DECLARE vDeliveryMethodId INT; - DECLARE vAgencyMode INT; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - SET vSelf = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT a.agencyModeFk, a.id - INTO vAgencyMode, vAddressFk - FROM vn.address a - WHERE a.id = vAddressFk; - - SELECT deliveryMethodFk INTO vDeliveryMethodId - FROM vn.agencyMode am - WHERE am.id = vAgencyMode; - - IF vCompany IS NULL - THEN - SELECT defaultCompanyFk INTO vCompany - FROM orderConfig; - END IF; - - INSERT INTO `order` - SET - customer_id = account.myUser_getId(), - date_send = vLandingDate, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgencyMode, - address_id = vAddressFk, - source_app = 'WEB', - company_id = vCompany; - - SET vSelf = LAST_INSERT_ID(); - - CALL order_checkConfig(vSelf); - - COMMIT; +BEGIN +/** + * Crea una nueva orden para el usuario actual especificando + * una fecha de entrega. + * + * @param vSelf Id de la nueva orden + * @param vLandingDate Fecha de entrega + */ + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + DECLARE vAgencyMode INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + SET vSelf = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT a.agencyModeFk, a.id + INTO vAgencyMode, vAddressFk + FROM vn.address a + WHERE a.id = vAddressFk; + + SELECT deliveryMethodFk INTO vDeliveryMethodId + FROM vn.agencyMode am + WHERE am.id = vAgencyMode; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.myUser_getId(), + date_send = vLandingDate, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgencyMode, + address_id = vAddressFk, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + CALL order_checkConfig(vSelf); + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12732,62 +12732,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithDate`( - OUT vSelf INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithDate`( + OUT vSelf INT, vLandingDate DATE) -BEGIN -/** - * Crea una nueva orden para el usuario actual especificando - * una fecha de entrega. - * - * @param vSelf Id de la nueva orden - * @param vLandingDate Fecha de entrega - */ - DECLARE vCompany INT; - DECLARE vDeliveryMethodId INT; - DECLARE vAgencyMode INT; - DECLARE vAddress INT; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - SET vSelf = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT a.agencyModeFk, a.id - INTO vAgencyMode, vAddress - FROM myClient c - JOIN vn.address a ON a.id = c.defaultAddressFk; - - SELECT deliveryMethodFk INTO vDeliveryMethodId - FROM vn.agencyMode am - WHERE am.id = vAgencyMode; - - IF vCompany IS NULL - THEN - SELECT defaultCompanyFk INTO vCompany - FROM orderConfig; - END IF; - - INSERT INTO `order` - SET - customer_id = account.myUser_getId(), - date_send = vLandingDate, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgencyMode, - address_id = vAddress, - source_app = 'WEB', - company_id = vCompany; - - SET vSelf = LAST_INSERT_ID(); - - CALL order_checkConfig(vSelf); - - COMMIT; +BEGIN +/** + * Crea una nueva orden para el usuario actual especificando + * una fecha de entrega. + * + * @param vSelf Id de la nueva orden + * @param vLandingDate Fecha de entrega + */ + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + SET vSelf = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT a.agencyModeFk, a.id + INTO vAgencyMode, vAddress + FROM myClient c + JOIN vn.address a ON a.id = c.defaultAddressFk; + + SELECT deliveryMethodFk INTO vDeliveryMethodId + FROM vn.agencyMode am + WHERE am.id = vAgencyMode; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.myUser_getId(), + date_send = vLandingDate, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgencyMode, + address_id = vAddress, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + CALL order_checkConfig(vSelf); + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12967,7 +12967,7 @@ BEGIN SELECT t.id ticketFk FROM myTicket t WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); - + CALL vn.ticketGetTotal; SELECT v.id, IFNULL(v.landed, v.shipped) landed, @@ -13210,7 +13210,7 @@ BEGIN IF vDone THEN LEAVE l; END IF; - + SET vAdd = vAmount - MOD(vAmount, vGrouping); SET vAmount = vAmount - vAdd; @@ -13226,7 +13226,7 @@ BEGIN rate = vRate, amount = vAdd, price = vPrice; - + SET vRow = LAST_INSERT_ID(); INSERT INTO orderRowComponent (rowFk, componentFk, price) @@ -13244,7 +13244,7 @@ BEGIN IF vAmount > 0 THEN CALL util.throw ('AMOUNT_NOT_MATCH_GROUPING'); END IF; - + COMMIT; CALL vn.ticketCalculatePurge; END ;; @@ -13287,10 +13287,10 @@ BEGIN CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT itemFk FROM orderRow + SELECT itemFk FROM orderRow WHERE orderFk = vSelf GROUP BY itemFk; - + CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -13890,7 +13890,7 @@ BEGIN INTO vDelivery, vAddress, vAgencyMode FROM `order` WHERE id = vSelf; - + CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable; @@ -13932,7 +13932,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; CREATE TEMPORARY TABLE tmp.addressCompany (INDEX (addressFk, companyFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT DISTINCT o.address_id addressFk, o.company_id companyFk FROM tmp.`order` tmpOrder JOIN hedera.`order` o ON o.id = tmpOrder.orderFk; @@ -13967,7 +13967,7 @@ BEGIN JOIN vn.taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount; CREATE TEMPORARY TABLE tmp.orderAmount (INDEX (orderFk)) @@ -13976,7 +13976,7 @@ BEGIN SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax FROM tmp.orderTax GROUP BY orderFk, `code`; - + DROP TEMPORARY TABLE tmp.addressTaxArea; END ;; DELIMITER ; @@ -14046,7 +14046,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.`order` ENGINE = MEMORY SELECT vSelf orderFk; - + CALL order_getTax; SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0) @@ -14137,7 +14137,7 @@ proc: BEGIN FROM orderRow r JOIN orderRowComponent c ON c.rowFk = r.id WHERE r.orderFk = vSelf; - + UPDATE orderRow r LEFT JOIN tmp.ticketComponentPrice p ON p.warehouseFk = r.warehouseFk @@ -14162,7 +14162,7 @@ proc: BEGIN ON t.id = c.componentFk AND (t.classRate IS NULL OR t.classRate = r.rate) WHERE r.orderFk = vSelf; - + CALL vn.ticketCalculatePurge; END IF; @@ -14506,13 +14506,13 @@ p: BEGIN 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 ; @@ -14545,7 +14545,7 @@ BEGIN UPDATE userSession SET userVisitFk = vUserVisit WHERE ssid = vSsid; - + DELETE FROM userSession WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW()); END ;; @@ -14669,7 +14669,7 @@ BEGIN UPDATE visitAgent SET firstAccessFk = vAccessId WHERE id = vAgentId; END IF; - + -- Returns the visit info SELECT vVisit visit, vAccessId access; @@ -15378,7 +15378,7 @@ BEGIN WHILE vI < vLen DO SET vChr = SUBSTR(vPhone, vI + 1, 1); - + IF vChr REGEXP '^[0-9]$' THEN SET vNewPhone = CONCAT(vNewPhone, vChr); @@ -15386,7 +15386,7 @@ BEGIN THEN SET vNewPhone = CONCAT(vNewPhone, '00'); END IF; - + SET vI = vI + 1; END WHILE; @@ -15484,19 +15484,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10)) -BEGIN - - /* - * Devuelve la extensión pbx del usuario - * - * @param vUserId Id del usuario - * - */ - - SELECT extension - FROM sip s - WHERE s.user_id = vUserId; - +BEGIN + + /* + * Devuelve la extensión pbx del usuario + * + * @param vUserId Id del usuario + * + */ + + SELECT extension + FROM sip s + WHERE s.user_id = vUserId; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16506,22 +16506,22 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RET READS SQL DATA BEGIN /** - * Devuelve la correspondencía del código de empresa de sage. + * Devuelve la correspondencía del código de empresa de sage. * Tiene en cuenta el entorno - * + * * @param vSelf Id de empresa de verdnatura * @return Código de empresa sage */ DECLARE vCompanySageFk INT(2); - - SELECT IF(c.environment = 'production', - co.companyCode, + + SELECT IF(c.environment = 'production', + co.companyCode, co.companyCodeTest ) INTO vCompanySageFk FROM util.config c JOIN vn.company co WHERE co.id = vCompanyFk; - + RETURN vCompanySageFk; END ;; DELIMITER ; @@ -16561,29 +16561,29 @@ BEGIN DECLARE vBookEntries TEXT; SELECT SiglaNacion INTO vCountryCanariasCode - FROM Naciones + FROM Naciones WHERE Nacion ='ISLAS CANARIAS'; SELECT SiglaNacion INTO vCountryCeutaMelillaCode - FROM Naciones + FROM Naciones WHERE Nacion ='CEUTA Y MELILLA'; SELECT CodigoTransaccion INTO vDuaTransactionFk FROM TiposTransacciones WHERE Transaccion = 'Import. bienes y serv. corrientes pdte. liquidar'; - - SELECT CodigoIva INTO vTaxImportFk + + SELECT CodigoIva INTO vTaxImportFk FROM TiposIva - WHERE Iva = 'IVA 21% importaciones'; - - SELECT CodigoIva INTO vTaxImportReducedFk + WHERE Iva = 'IVA 21% importaciones'; + + SELECT CodigoIva INTO vTaxImportReducedFk FROM TiposIva WHERE Iva = 'IVA 10% importaciones'; - SELECT CodigoIva INTO vTaxImportSuperReducedFk + SELECT CodigoIva INTO vTaxImportSuperReducedFk FROM TiposIva WHERE Iva = 'H.P. IVA Soportado Impor 4%'; - + SELECT CodigoTransaccion INTO vTransactionExportFk FROM TiposTransacciones WHERE Transaccion = 'Exportaciones definitivas'; @@ -16593,22 +16593,22 @@ BEGIN WHERE Transaccion = 'Envíos definitivos a Canarias, Ceuta y Melilla'; SELECT codeSage INTO vInvoiceTypeInformativeCode - FROM invoiceType WHERE code ='informative'; + FROM invoiceType WHERE code ='informative'; SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; - + TRUNCATE movContaIVA; - - DELETE FROM movConta - WHERE enlazadoSage = FALSE + + DELETE FROM movConta + WHERE enlazadoSage = FALSE AND Asiento <> 1 ; - + CALL clientSupplier_add(vCompanyFk); CALL pgc_add(vCompanyFk); CALL invoiceOut_manager(vYear, vCompanyFk); CALL invoiceIn_manager(vYear, vCompanyFk); - + INSERT INTO movConta(TipoEntrada, Ejercicio, CodigoEmpresa, @@ -16684,7 +16684,7 @@ BEGIN BaseImponibleOriginal, CuotaIvaOriginal, ClaseAbonoRectificativas, - RecargoEquivalenciaOriginal, + RecargoEquivalenciaOriginal, LibreA1, CodigoIva1, CodigoIva2, @@ -16697,8 +16697,8 @@ BEGIN Intracomunitaria ) SELECT 'EN' TipoEntrada, - YEAR(x.FECHA) Ejercicio, - company_getCode(vCompanyFk) AS CodigoEmpresa, + YEAR(x.FECHA) Ejercicio, + company_getCode(vCompanyFk) AS CodigoEmpresa, x.ASIEN Asiento, IF(EURODEBE <> 0 OR (EURODEBE = 0 AND EUROHABER IS NULL), 'D', 'H') CargoAbono, x.SUBCTA CodigoCuenta, @@ -16783,63 +16783,63 @@ BEGIN mci.IvaDeducible4, mci.Intracomunitaria FROM vn.XDiario x - LEFT JOIN movContaIVA mci ON mci.id = x.id - LEFT JOIN (SELECT * + LEFT JOIN movContaIVA mci ON mci.id = x.id + LEFT JOIN (SELECT * FROM (SELECT DISTINCT ASIEN, FECREGCON, FECHA_EX FROM vn.XDiario - WHERE enlazadoSage = FALSE + WHERE enlazadoSage = FALSE ORDER BY ASIEN, FECREGCON DESC, FECHA_EX DESC LIMIT 10000000000000000000 ) sub GROUP BY ASIEN - )sub2 ON sub2.ASIEN = x.ASIEN + )sub2 ON sub2.ASIEN = x.ASIEN LEFT JOIN ( SELECT DISTINCT(account),cu.code FROM vn.bank b JOIN vn.currency cu ON cu.id = b.currencyFk WHERE cu.code <> 'EUR' -- no se informa cuando la divisa en EUR - )sub3 ON sub3.account = x.SUBCTA - WHERE x.enlazadoSage = FALSE + )sub3 ON sub3.account = x.SUBCTA + WHERE x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo; -- Metálicos UPDATE movConta m - JOIN (SELECT Asiento, - c.socialName name, - c.fi, - n.SiglaNacion, - m.CodigoCuenta, + JOIN (SELECT Asiento, + c.socialName name, + c.fi, + n.SiglaNacion, + m.CodigoCuenta, m.Contrapartida - FROM movConta m + FROM movConta m LEFT JOIN vn.client c ON c.id = IF(m.CargoAbono = 'H', CAST(SUBSTRING(m.CodigoCuenta, 3, LENGTH(m.CodigoCuenta)) AS UNSIGNED), CAST(SUBSTRING(m.Contrapartida, 3, LENGTH(m.Contrapartida)) AS UNSIGNED)) - LEFT JOIN Naciones n ON n.countryFk = c.countryFk - WHERE m.Metalico347 = TRUE - AND m.enlazadoSage = FALSE - )sub ON m.Asiento = sub.Asiento + LEFT JOIN Naciones n ON n.countryFk = c.countryFk + WHERE m.Metalico347 = TRUE + AND m.enlazadoSage = FALSE + )sub ON m.Asiento = sub.Asiento SET m.Metalico347 = TRUE, m.TipoFactura = vInvoiceTypeInformativeCode, m.CifDni = sub.fi, m.Nombre = sub.name, - m.SiglaNacion = sub.SiglaNacion + m.SiglaNacion = sub.SiglaNacion WHERE m.enlazadoSage = FALSE; UPDATE movConta m SET m.Metalico347 = FALSE, m.TipoFactura = '' - WHERE m.CargoAbono = 'D' - AND m.enlazadoSage = FALSE; + WHERE m.CargoAbono = 'D' + AND m.enlazadoSage = FALSE; -- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación - DELETE cp + DELETE cp FROM clientesProveedores cp - LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta + LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta AND mc.enlazadoSage = FALSE WHERE mc.codigoCuenta IS NULL; -- Elimina cuentas contables que no se utilizarán en la importación - DELETE pc - FROM planCuentasPGC pc + DELETE pc + FROM planCuentasPGC pc LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta AND mc.enlazadoSage = FALSE WHERE mc.codigoCuenta IS NULL; @@ -16879,7 +16879,7 @@ BEGIN AND mci.enlazadoSage = FALSE AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci AND ti.Iva = 'I.V.A. 21%'; - + UPDATE movConta mci JOIN vn.XDiario x ON x.ASIEN = mci.Asiento JOIN TiposIva ti ON ti.CodigoIva = x.IVA @@ -16897,19 +16897,19 @@ BEGIN AND ti.Iva = 'I.V.A. 4%'; -- Rectificativas - UPDATE movConta mci - JOIN (SELECT x.ASIEN, x.FECHA_RT, x.SERIE_RT, x.FACTU_RT - FROM movConta mci + UPDATE movConta mci + JOIN (SELECT x.ASIEN, x.FECHA_RT, x.SERIE_RT, x.FACTU_RT + FROM movConta mci JOIN vn.XDiario x ON x.ASIEN = mci.Asiento - WHERE mci.TipoRectificativa > 0 - AND mci.enlazadoSage = FALSE + WHERE mci.TipoRectificativa > 0 + AND mci.enlazadoSage = FALSE AND x.FACTU_RT IS NOT NULL GROUP BY x.ASIEN ) sub ON sub.ASIEN = mci.Asiento - SET mci.EjercicioFacturaOriginal = YEAR(sub.FECHA_RT), - mci.SerieFacturaOriginal = sub.SERIE_RT, - mci.NumeroFacturaOriginal = sub.FACTU_RT - WHERE mci.TipoRectificativa > 0 AND + SET mci.EjercicioFacturaOriginal = YEAR(sub.FECHA_RT), + mci.SerieFacturaOriginal = sub.SERIE_RT, + mci.NumeroFacturaOriginal = sub.FACTU_RT + WHERE mci.TipoRectificativa > 0 AND mci.enlazadoSage = FALSE ; -- Exportaciones Andorras y Canarias cambia TT (la cuenta es compartida) @@ -16918,24 +16918,24 @@ BEGIN CodigoTransaccion2 = IF(CodigoTransaccion2 = 0, 0, vTransactionExportTaxFreeFk), CodigoTransaccion3 = IF(CodigoTransaccion3 = 0, 0, vTransactionExportTaxFreeFk), CodigoTransaccion4 = IF(CodigoTransaccion4 = 0, 0, vTransactionExportTaxFreeFk) - WHERE enlazadoSage = FALSE - AND (CodigoTransaccion1 = vTransactionExportFk - OR CodigoTransaccion2 = vTransactionExportFk - OR CodigoTransaccion3 = vTransactionExportFk - OR CodigoTransaccion4 = vTransactionExportFk) + WHERE enlazadoSage = FALSE + AND (CodigoTransaccion1 = vTransactionExportFk + OR CodigoTransaccion2 = vTransactionExportFk + OR CodigoTransaccion3 = vTransactionExportFk + OR CodigoTransaccion4 = vTransactionExportFk) AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, vCountryCeutaMelillaCode COLLATE utf8mb3_unicode_ci); UPDATE movConta mc SET CodigoDivisa = 'USD', FactorCambio = TRUE, ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, ImporteAsiento / ImporteDivisa, ImporteCambio) AS DECIMAL( 10, 2))) - WHERE enlazadoSage = FALSE + WHERE enlazadoSage = FALSE AND (ImporteCambio <> 0 OR ImporteDivisa <> 0 OR FactorCambio); UPDATE movConta mc SET importeDivisa= -importeDivisa - WHERE enlazadoSage = FALSE - AND importeDivisa > 0 + WHERE enlazadoSage = FALSE + AND importeDivisa > 0 AND ImporteAsiento < 0; -- Comprobación que los importes e ivas sean correctos, avisa vía CAU @@ -16946,11 +16946,11 @@ BEGIN WHERE mc.enlazadoSage = FALSE GROUP BY mc.Asiento)sub JOIN (SELECT x.ASIEN, SUM(IFNULL(x.EURODEBE,0) + IFNULL(x.EUROHABER,0)) amount - FROM vn.XDiario x + FROM vn.XDiario x WHERE x.enlazadoSage = FALSE GROUP BY ASIEN)sub2 ON sub2.ASIEN = sub.Asiento WHERE sub.amount <> sub2.amount - UNION ALL + UNION ALL SELECT sub.Asiento FROM (SELECT Asiento, SUM(BaseIva1 + BaseIva2 + BaseIva3 + BaseIva4) amountTaxableBase FROM movConta @@ -16959,13 +16959,13 @@ BEGIN GROUP BY Asiento) sub JOIN (SELECT ASIEN, SUM(BASEEURO) amountTaxableBase FROM (SELECT ASIEN, SUM(BASEEURO) BASEEURO - FROM vn.XDiario - WHERE FACTURA + FROM vn.XDiario + WHERE FACTURA AND auxiliar <> '*' AND enlazadoSage = FALSE GROUP BY FACTURA, ASIEN)sub3 GROUP BY ASIEN) sub2 ON sub2.ASIEN = sub.Asiento - WHERE sub.amountTaxableBase<>sub2.amountTaxableBase + WHERE sub.amountTaxableBase<>sub2.amountTaxableBase AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase) sub; IF vBookEntries IS NOT NULL THEN @@ -16994,18 +16994,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`(vCompanyFk INT) BEGIN /** - * Prepara los datos de clientes y proveedores para exportarlos a Sage + * Prepara los datos de clientes y proveedores para exportarlos a Sage * @vCompanyFk Empresa dela que se quiere trasladar datos */ DECLARE vCountryCeutaMelillaFk INT; DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); SELECT SiglaNacion INTO vCountryCanariasCode - FROM Naciones + FROM Naciones WHERE Nacion ='ISLAS CANARIAS'; SELECT CodigoNacion, SiglaNacion INTO vCountryCeutaMelillaFk, vCountryCeutaMelillaCode - FROM Naciones + FROM Naciones WHERE Nacion ='CEUTA Y MELILLA'; TRUNCATE TABLE clientesProveedores; @@ -17036,7 +17036,7 @@ BEGIN CodigoRetencion, Email1, iban) - SELECT + SELECT company_getCode(vCompanyFk), 'C', c.id, @@ -17053,12 +17053,12 @@ BEGIN IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion), IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'), - IF(cu.code IN('ES','EX'), - 1, + IF(cu.code IN('ES','EX'), + 1, IF((cu.isUeeMember AND c.isVies), 2, 4)), IFNULL(c.taxTypeSageFk,0), - IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, - IF(@isCeutaMelilla, 'CEUTA Y MELILLA', IF (@isCanarias, 'ISLAS CANARIAS', n.Nacion)), + IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, + IF(@isCeutaMelilla, 'CEUTA Y MELILLA', IF (@isCanarias, 'ISLAS CANARIAS', n.Nacion)), n.Nacion), IFNULL(c.phone, ''), IFNULL(c.mobile, ''), @@ -17072,7 +17072,7 @@ BEGIN LEFT JOIN Naciones n ON n.countryFk = cu.id LEFT JOIN vn.province p ON p.id = c.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id - WHERE c.isRelevant + WHERE c.isRelevant AND clm.companyFk = vCompanyFk UNION ALL SELECT company_getCode(vCompanyFk), @@ -17101,15 +17101,15 @@ BEGIN IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''), IFNULL(iban, '') FROM vn.supplier s - JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id + JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id LEFT JOIN vn.country co ON co.id = s.countryFk LEFT JOIN Naciones n ON n.countryFk = co.id LEFT JOIN vn.province p ON p.id = s.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id - WHERE pl.companyFk = vCompanyFk AND - s.isActive AND + WHERE pl.companyFk = vCompanyFk AND + s.isActive AND s.nif <> '' GROUP BY pl.supplierFk, pl.companyFk; END ;; @@ -17132,10 +17132,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vX BEGIN /** * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * * @vInvoiceInFk Factura recibida * @vXDiarioFk Id tabla XDiario - */ + */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vBase DOUBLE; DECLARE vVat DOUBLE; @@ -17151,24 +17151,24 @@ BEGIN DECLARE vInvoiceTypeReceived VARCHAR(1); DECLARE vInvoiceTypeInformative VARCHAR(1); - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT it.taxableBase, CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), t.PorcentajeIva, it.transactionTypeSageFk, it.taxTypeSageFk, t.isIntracommunity, - tt.ClaveOperacionDefecto + tt.ClaveOperacionDefecto FROM vn.invoiceIn i - JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id + JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk LEFT JOIN vn.dua d ON d.id = vInvoiceInFk - WHERE i.id = vInvoiceInFk + WHERE i.id = vInvoiceInFk AND d.id IS NULL; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; @@ -17191,22 +17191,22 @@ BEGIN vTaxCode, vIsIntracommunity, vOperationCode; - - IF vDone THEN + + IF vDone THEN LEAVE l; END IF; - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; - IF vOperationCode IS NOT NULL THEN + IF vOperationCode IS NOT NULL THEN UPDATE movContaIVA SET ClaveOperacionFactura = vOperationCode WHERE id = vXDiarioFk; END IF; - + SET vCounter = vCounter + 1; - CASE vCounter + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -17242,21 +17242,21 @@ BEGIN WHERE id = vXDiarioFk; ELSE SELECT vXDiarioFk INTO vXDiarioFk; - END CASE; + END CASE; IF vIsIntracommunity THEN UPDATE movContaIVA SET Intracomunitaria = TRUE WHERE id = vXDiarioFk; END IF; - - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; - + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + END LOOP; CLOSE vCursor; - + UPDATE movContaIVA mci JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk JOIN vn.XDiario x ON x.id = mci.id @@ -17268,11 +17268,11 @@ BEGIN mci.Serie = ii.serial, mci.Factura = ii.serialNumber, mci.FechaFactura = ii.issued, - mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + - IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + - IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), - mci.TipoFactura = IF(id.id, IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), vInvoiceTypeReceived), + mci.TipoFactura = IF(id.id, IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), vInvoiceTypeReceived), mci.CodigoCuentaFactura = x.SUBCTA, mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), mci.Nombre = s.name, @@ -17300,7 +17300,7 @@ BEGIN JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase FROM vn.XDiario x1 JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN - WHERE x2.BASEEURO <> 0 + WHERE x2.BASEEURO <> 0 AND x1.id = vXDiarioFk )sub JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' @@ -17308,8 +17308,8 @@ BEGIN mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), mci.PorRetencion = t.PorcentajeRetencion, - mci.ImporteRetencion = iit.taxableBase * - 1 - WHERE mci.id = vXDiarioFk + mci.ImporteRetencion = iit.taxableBase * - 1 + WHERE mci.id = vXDiarioFk AND e.name = 'Retenciones' AND id.id IS NULL; @@ -17332,10 +17332,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * Traslada la info de contabilidad relacionada con las facturas recibidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17347,22 +17347,22 @@ BEGIN DECLARE vAccountTaxOutstanding VARCHAR(10); DECLARE vInvoiceTypeSended VARCHAR(1); DECLARE vCursor CURSOR FOR - SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, + SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, x.id XDiarioFk - FROM vn.XDiario x + FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) FROM vn.XDiario x LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id - WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) - AND x.enlazadoSage = FALSE + WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) + AND x.enlazadoSage = FALSE AND x.FECHA BETWEEN vDatedFrom AND vDatedTo - AND x.empresa_id = vCompanyFk + AND x.empresa_id = vCompanyFk ) sub ON sub.ASIEN = x.ASIEN WHERE x.CLAVE IS NOT NULL; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; @@ -17376,15 +17376,15 @@ BEGIN SELECT codeSage INTO vInvoiceTypeSended FROM invoiceType WHERE `code` ='sended'; - + DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua; CREATE TEMPORARY TABLE tmp.invoiceDua - SELECT x.id + SELECT x.id FROM vn.XDiario x JOIN vn.company c ON c.id = x.empresa_id JOIN (SELECT ASIEN - FROM vn.XDiario x - WHERE x.enlazadoSage = FALSE + FROM vn.XDiario x + WHERE x.enlazadoSage = FALSE AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci AND x.FECHA BETWEEN vDatedFrom AND vDatedTo )sub ON sub.ASIEN = x.ASIEN @@ -17403,7 +17403,7 @@ BEGIN FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo - UNION ALL + UNION ALL SELECT d.id, d.code, vSerialDua, @@ -17412,8 +17412,8 @@ BEGIN FALSE, d.id, '' -- EUROS - FROM vn.dua d - WHERE d.issued IS NOT NULL + FROM vn.dua d + WHERE d.issued IS NOT NULL AND code IS NOT NULL; OPEN vCursor; @@ -17421,7 +17421,7 @@ BEGIN l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; CALL invoiceIn_add(vInvoiceFk, vXDiarioFk); @@ -17509,21 +17509,21 @@ BEGIN JOIN (SELECT x.ASIEN, x.id FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) ASIEN - FROM vn.XDiario x + FROM vn.XDiario x JOIN (SELECT DISTINCT(ASIEN) FROM vn.XDiario x - WHERE SUBCTA LIKE '472%' + WHERE SUBCTA LIKE '472%' AND x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo ) sub ON sub.ASIEN = x.ASIEN WHERE x.SUBCTA LIKE '477%' )sub2 ON sub2.ASIEN = x.ASIEN - WHERE x.CONTRA IS NOT NULL + WHERE x.CONTRA IS NOT NULL AND x.SUBCTA LIKE '477%' GROUP BY x.ASIEN )sub3 ON sub3.ASIEN = x.ASIEN; - + INSERT INTO movContaIVA (`id`, `CodigoDivisa`, @@ -17594,9 +17594,9 @@ BEGIN `FechaGrabacion`, `Intracomunitaria`, `moveData`) - SELECT * + SELECT * FROM tmp.movContaIVA; - + DROP TEMPORARY TABLE tmp.movContaIVA; END ;; @@ -17618,10 +17618,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vMaxLengthName INT DEFAULT 35; @@ -17641,12 +17641,12 @@ BEGIN DECLARE vHasCustomsAccountingNote BOOL; DECLARE vCursor CURSOR FOR - SELECT oit.taxableBase, - oit.vat, - pgc.rate, - pgc.mod347, - pgcRE.rate, - oitRE.vat, + SELECT oit.taxableBase, + oit.vat, + pgc.rate, + pgc.mod347, + pgcRE.rate, + oitRE.vat, tc.transactionCode, tc.taxCode, tc.isIntracommunity, @@ -17655,7 +17655,7 @@ BEGIN JOIN vn.pgc ON pgc.code = oit.pgcFk LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk - LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk + LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk AND oitRE.pgcFk = e.equFk LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci' @@ -17671,12 +17671,12 @@ BEGIN WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk); SELECT codeSage INTO vInvoiceTypeSended - FROM invoiceType + FROM invoiceType WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended'); - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; - + INSERT INTO movContaIVA(id) VALUES (vXDiarioFk); OPEN vCursor; @@ -17693,13 +17693,13 @@ BEGIN vIsIntracommunity, vOperationCode; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; SET vCounter = vCounter + 1; - - CASE vCounter + + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -17740,7 +17740,7 @@ BEGIN CodigoTransaccion4 = vTransactionCode, CodigoIva4 = vTaxCode WHERE id = vXDiarioFk; - END CASE; + END CASE; UPDATE movContaIVA SET Exclusion347 = NOT vMod347, @@ -17751,7 +17751,7 @@ BEGIN END LOOP; CLOSE vCursor; - + UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk @@ -17776,25 +17776,25 @@ BEGIN mci.MantenerAsiento = TRUE, mci.FechaFacturaOriginal = x.FECHA_EX WHERE mci.id = vXDiarioFk; - + SELECT correctedFk INTO vInvoiceOutCorrectedFk FROM vn.invoiceCorrection WHERE correctingFk = vInvoiceOutFk; - - IF vInvoiceOutCorrectedFk THEN + + IF vInvoiceOutCorrectedFk THEN UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk - JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, + JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat, SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ FROM vn.invoiceOutTax iot - LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk + LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk ) tax JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' SET mci.TipoRectificativa = 2, - mci.ClaseAbonoRectificativas = 1, + mci.ClaseAbonoRectificativas = 1, mci.FechaFacturaOriginal = i.issued, mci.FechaOperacion = i.issued, mci.BaseImponibleOriginal = tax.taxableBase, @@ -17825,10 +17825,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17845,7 +17845,7 @@ BEGIN JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk FROM vn.XDiario x WHERE x.enlazadoSage = FALSE - AND x.FACTURA + AND x.FACTURA AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo GROUP BY refFk @@ -17854,19 +17854,19 @@ BEGIN )sub2 ON sub2.refFk = i.ref; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; - + OPEN vCursor; l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; - + CALL invoiceOut_add(vInvoiceFk, vXDiarioFk); END LOOP; @@ -17892,7 +17892,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT) BEGIN /** - * Añade cuentas del plan general contable para exportarlos a Sage + * Añade cuentas del plan general contable para exportarlos a Sage * @vCompanyFk Empresa de la que se quiere trasladar datos */ TRUNCATE TABLE planCuentasPGC; @@ -17902,25 +17902,25 @@ BEGIN CodigoCuenta, Cuenta, ClienteOProveedor) - SELECT * + SELECT * FROM (SELECT company_getCode(vCompanyFk) companyFk, e.id accountFk, UCASE(e.name), '' FROM vn.expence e - UNION + UNION SELECT company_getCode(vCompanyFk), - b.account, + b.account, UCASE(b.bank), - '' + '' FROM vn.bank b WHERE b.isActive AND b.`account` - UNION + UNION SELECT CodigoEmpresa, CodigoCuenta, Nombre, - ClienteOProveedor + ClienteOProveedor FROM clientesProveedores)sub GROUP BY companyFk, accountFk; END ;; @@ -18190,7 +18190,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18314,7 +18314,7 @@ DELIMITER ;; BEGIN SET NEW.lack = NEW.quantity; SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18525,7 +18525,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSupplied = 0; OPEN vPicks; @@ -18541,7 +18541,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity); - + UPDATE outbound SET isSync = FALSE, lack = lack + vPickGranted @@ -18621,7 +18621,7 @@ BEGIN END IF; SET vSupplied = LEAST(vAvailable, vLack); - + IF vSupplied > 0 THEN SET vAvailable = vAvailable - vSupplied; UPDATE outbound @@ -18634,7 +18634,7 @@ BEGIN SET vSupplied = vSupplied + vSuppliedFromRequest; SET vAvailable = vAvailable - vSuppliedFromRequest; END IF; - + IF vSupplied > 0 THEN CALL inbound_addPick(vSelf, vOutboundFk, vSupplied); END IF; @@ -18763,7 +18763,7 @@ BEGIN DO RELEASE_LOCK('stock.log_sync'); RESIGNAL; END; - + IF !GET_LOCK('stock.log_sync', 30) THEN CALL util.throw('Lock timeout exceeded'); END IF; @@ -19234,7 +19234,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity); - + UPDATE inbound SET isSync = FALSE, available = available + vPickGranted @@ -19668,11 +19668,11 @@ BEGIN WHILE vI < vLen DO SET vSpaceIni = vI; - + WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO SET vI = vI + 1; END WHILE; - + SET vWordIni = vI; SET vI = vWordIni + 1; @@ -19709,11 +19709,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARC BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.crypt(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19735,11 +19735,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey V BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.cryptOff(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19907,7 +19907,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1) DETERMINISTIC -BEGIN +BEGIN RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2); @@ -19936,7 +19936,7 @@ BEGIN */ DECLARE vHashlen INT UNSIGNED; DECLARE vOpad, vIpad TINYBLOB; - + CASE vAlg WHEN 224 THEN SET vHashlen = 64; WHEN 256 THEN SET vHashlen = 64; @@ -19944,16 +19944,16 @@ BEGIN WHEN 512 THEN SET vHashlen = 128; ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED'); END CASE; - + IF LENGTH(vKey) > vHashlen THEN SET vKey = UNHEX(SHA2(vKey, vAlg)); END IF; - + SET vKey = RPAD(vKey, vHashlen, 0x00); - + SET vIpad = stringXor(vKey, 0x36); SET vOpad = stringXor(vKey, 0x5C); - + RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg); END ;; DELIMITER ; @@ -19976,7 +19976,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyi BEGIN RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20049,7 +20049,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime READS SQL DATA BEGIN - + RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59'); END ;; @@ -20077,7 +20077,7 @@ BEGIN * modo 3. */ DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100); - + IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN RETURN vYearWeek + 1; ELSE @@ -20188,16 +20188,16 @@ BEGIN */ DECLARE vLen, vPos INT UNSIGNED; DECLARE vResult MEDIUMBLOB; - + SET vLen = LENGTH(vString); SET vPos = 1; SET vResult = ''; - + WHILE vPos <= vLen DO SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0')); SET vPos = vPos + 1; END WHILE; - + RETURN UNHEX(vResult); END ;; DELIMITER ; @@ -20307,11 +20307,11 @@ BEGIN IF vYear = vCurYear THEN RETURN 'curYear'; END IF; - + IF vYear = vCurYear - 1 THEN RETURN 'lastYear'; END IF; - + IF vYear = vCurYear - 2 THEN RETURN 'twoYearsAgo'; END IF; @@ -20398,10 +20398,10 @@ BEGIN */ SET vChain = CONCAT('%', vChain, '%'); SET vCompare = CONCAT('%', vCompare, '%'); - SELECT * FROM + SELECT * FROM ( SELECT t1.* FROM - ( + ( SELECT `db`, `name`, @@ -20428,7 +20428,7 @@ BEGIN 'TRIGGER', `ACTION_STATEMENT`, NULL, - NULL + NULL FROM `information_schema`.`TRIGGERS` WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci UNION ALL @@ -20438,7 +20438,7 @@ BEGIN 'VIEW', `VIEW_DEFINITION`, NULL, - NULL + NULL FROM `information_schema`.`VIEWS` WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci ) t1 @@ -20469,7 +20469,7 @@ BEGIN 'TRIGGER', `ACTION_STATEMENT`, NULL, - NULL + NULL FROM `information_schema`.`TRIGGERS` WHERE `ACTION_STATEMENT` LIKE vCompare COLLATE utf8_general_ci UNION ALL @@ -20479,7 +20479,7 @@ BEGIN 'VIEW', `VIEW_DEFINITION`, NULL, - NULL + NULL FROM `information_schema`.`VIEWS` WHERE `VIEW_DEFINITION` LIKE vCompare COLLATE utf8_general_ci) t2 ON t2.name = t1.name ORDER BY t1.`db`, t1.`name` @@ -20510,7 +20510,7 @@ BEGIN * @param vValue Valor de la variable */ DECLARE vIndex INT DEFAULT INSTR(USER(), '@'); - + INSERT INTO debug SET `connectionId` = CONNECTION_ID(), `user` = LEFT(USER(), vIndex - 1), @@ -20577,7 +20577,7 @@ BEGIN SET vChain = CONCAT('%', vChain, '%'); SELECT * FROM - ( + ( SELECT `routine_schema` `schema`, `routine_name` `name`, @@ -20604,7 +20604,7 @@ BEGIN 'TRIGGER', `ACTION_STATEMENT`, NULL, - NULL + NULL FROM `information_schema`.`TRIGGERS` WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci UNION ALL @@ -20614,7 +20614,7 @@ BEGIN 'VIEW', `VIEW_DEFINITION`, NULL, - NULL + NULL FROM `information_schema`.`VIEWS` WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci ) t @@ -20828,7 +20828,7 @@ BEGIN INSERT INTO tmp.time (dated) VALUES (vCurrentDate); SET vCurrentDate = DATE_ADD(vCurrentDate, INTERVAL 1 DAY); END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21205,11 +21205,11 @@ BEGIN END IF; IF NEW.isEqualizated IS NULL THEN - SELECT isEqualizated + SELECT isEqualizated INTO vIsEqualizated FROM client WHERE id = NEW.clientFk; - + SET NEW.isEqualizated = vIsEqualizated; END IF; END */;; @@ -21231,11 +21231,11 @@ DELIMITER ;; BEFORE UPDATE ON `address` FOR EACH ROW BEGIN - + IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); END IF; - + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN CALL pbx.phone_isValid(NEW.mobile); END IF; @@ -21261,16 +21261,16 @@ DELIMITER ;; BEGIN -- Recargos de equivalencia distintos implican facturacion por consignatario IF NEW.isEqualizated != OLD.isEqualizated THEN - IF + IF (SELECT COUNT(*) FROM ( SELECT DISTINCT (isEqualizated = FALSE) as Equ - FROM address + FROM address WHERE clientFk = NEW.clientFk ) t1 ) > 1 - THEN - UPDATE client + THEN + UPDATE client SET hasToInvoiceByAddress = TRUE WHERE id = NEW.clientFk; END IF; @@ -21278,10 +21278,10 @@ BEGIN IF NEW.isDefaultAddress AND NEW.isActive = FALSE THEN CALL util.throw ('Cannot desactivate the default address'); END IF; - + IF NOT (NEW.isEqualizated <=> OLD.isEqualizated) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.addressFk = NEW.id AND t.refFk IS NULL; END IF; @@ -21614,8 +21614,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BI` BEFORE INSERT ON `autonomy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk)); END */;; @@ -21665,7 +21665,7 @@ DELIMITER ;; AFTER DELETE ON `autonomy` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21741,7 +21741,7 @@ DELIMITER ;; BEFORE INSERT ON `awb` FOR EACH ROW BEGIN - + SET NEW.year= year(util.VN_CURDATE()); @@ -22098,11 +22098,11 @@ DELIMITER ;; BEFORE INSERT ON `budgetNotes` FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -22156,7 +22156,6 @@ CREATE TABLE `business` ( CONSTRAINT `business_departmentFk` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON UPDATE CASCADE, CONSTRAINT `business_occupationCodeFk` FOREIGN KEY (`occupationCodeFk`) REFERENCES `occupationCode` (`code`) ON UPDATE CASCADE, CONSTRAINT `business_workerBusinessAgreementFk` FOREIGN KEY (`workerBusinessAgreementFk`) REFERENCES `postgresql`.`labour_agreement` (`labour_agreement_id`) ON UPDATE CASCADE, - CONSTRAINT `business_workerBusinessCategoryFk` FOREIGN KEY (`workerBusinessCategoryFk`) REFERENCES `vn2008`.`payroll_categorias` (`codcategoria`) ON UPDATE CASCADE, CONSTRAINT `business_workerBusinessProfessionalCategoryFk` FOREIGN KEY (`workerBusinessProfessionalCategoryFk`) REFERENCES `postgresql`.`professional_category` (`professional_category_id`) ON UPDATE CASCADE, CONSTRAINT `business_workerBusinessTypeFk` FOREIGN KEY (`workerBusinessTypeFk`) REFERENCES `workerBusinessType` (`id`) ON UPDATE CASCADE, CONSTRAINT `business_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE @@ -22218,28 +22217,28 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE isOverlapping BOOL; - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN - + SELECT COUNT(*) > 0 INTO isOverlapping FROM business b WHERE (util.hasDateOverlapped( - NEW.started, + NEW.started, IFNULL(NEW.ended, b.started), b.started, IFNULL(b.ended, NEW.started)) OR (NEW.ended <=> NULL AND b.ended <=> NULL)) AND b.id <> OLD.id AND workerFk = OLD.workerFk; - - IF isOverlapping THEN + + IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; - + END IF; END */;; @@ -22485,7 +22484,7 @@ trig: BEGIN LEAVE trig; END IF; - IF @isTriggerDisabled THEN + IF @isTriggerDisabled THEN LEAVE trig; END IF; @@ -22591,12 +22590,12 @@ trig: BEGIN OR !(NEW.created <=> OLD.created) THEN CALL stock.log_add('buy', NEW.id, OLD.id); END IF; - + IF @isModeInventory THEN LEAVE trig; END IF; - IF @isTriggerDisabled THEN + IF @isTriggerDisabled THEN LEAVE trig; END IF; @@ -22606,24 +22605,24 @@ trig: BEGIN INTO vIsBuyerToBeEmailed, vLanded FROM entry e JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk + JOIN warehouse w ON w.id = t.warehouseInFk WHERE e.id = NEW.entryFk; - - SELECT it.workerFk, i.longName + + SELECT it.workerFk, i.longName INTO vBuyerFk, vItemName FROM itemCategory k JOIN itemType it ON it.categoryFk = k.id JOIN item i ON i.typeFk = it.id WHERE i.id = OLD.itemFk; - IF vIsBuyerToBeEmailed AND - vBuyerFk != account.myUser_getId() AND + IF vIsBuyerToBeEmailed AND + vBuyerFk != account.myUser_getId() AND vLanded = util.VN_CURDATE() THEN - IF !(NEW.itemFk <=> OLD.itemFk) OR - !(NEW.quantity <=> OLD.quantity) OR + IF !(NEW.itemFk <=> OLD.itemFk) OR + !(NEW.quantity <=> OLD.quantity) OR !(NEW.packing <=> OLD.packing) OR - !(NEW.grouping <=> OLD.grouping) OR - !(NEW.packageFk <=> OLD.packageFk) OR + !(NEW.grouping <=> OLD.grouping) OR + !(NEW.packageFk <=> OLD.packageFk) OR !(NEW.weight <=> OLD.weight) THEN CALL vn.mail_insert( CONCAT(account.user_getNameFromId(vBuyerFk),'@verdnatura.es'), @@ -22652,7 +22651,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeDelete` BEFORE DELETE ON buy FOR EACH ROW -BEGIN +BEGIN IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; @@ -22674,10 +22673,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_afterDelete` AFTER DELETE ON `buy` FOR EACH ROW -trig: BEGIN +trig: BEGIN DECLARE vValues VARCHAR(255); - IF @isTriggerDisabled THEN + IF @isTriggerDisabled THEN LEAVE trig; END IF; @@ -22980,7 +22979,7 @@ BEGIN FROM sale WHERE id = NEW.saleFk; - UPDATE claim + UPDATE claim SET ticketFk = vTicket WHERE id = NEW.claimFk; END */;; @@ -23378,7 +23377,7 @@ BEGIN END IF; SET NEW.accountingAccount = 4300000000 + NEW.id; - + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END */;; DELIMITER ; @@ -23406,19 +23405,19 @@ BEGIN IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); END IF; - + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN CALL pbx.phone_isValid(NEW.mobile); END IF; SELECT id INTO vPayMethodFk - FROM vn.payMethod + FROM vn.payMethod WHERE code = 'bankDraft'; - + IF NEW.payMethodFk = vPayMethodFk 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 @@ -23431,7 +23430,7 @@ BEGIN IF vText IS NOT NULL THEN - INSERT INTO mail(receiver, replyTo, `subject`, body) + INSERT INTO mail(receiver, replyTo, `subject`, body) SELECT CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), 'administracion@verdnatura.es', @@ -23442,16 +23441,16 @@ BEGIN LEFT JOIN account.account ac ON ac.id = u.id WHERE w.id = NEW.salesPersonFk; END IF; - + IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN - IF (SELECT COUNT(clientFk) + IF (SELECT COUNT(clientFk) FROM clientProtected WHERE clientFk = NEW.id ) > 0 THEN CALL util.throw("HAS_CLIENT_PROTECTED"); END IF; END IF; - + IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); END IF; @@ -23482,18 +23481,18 @@ BEGIN IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = 0 WHERE clientFk = NEW.id; - + UPDATE `address` SET isDefaultAddress = 1 - WHERE id = NEW.defaultAddressFk; + WHERE id = NEW.defaultAddressFk; END IF; IF NOT (NEW.provinceFk <=> OLD.provinceFk) OR NOT (NEW.isVies <=> OLD.isVies) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.clientFk = NEW.id AND t.refFk IS NULL; END IF; - + IF NOT NEW.isActive THEN UPDATE account.`user` SET active = FALSE @@ -23608,15 +23607,15 @@ DELIMITER ;; AFTER INSERT ON clientCredit FOR EACH ROW BEGIN - + DECLARE vSender VARCHAR(50); SELECT u.name INTO vSender FROM account.`user` u WHERE u.id = NEW.workerFk; - + IF vSender IN ('juanvi','pepe') THEN - + CALL `vn`.`mail_insert`('pako@verdnatura.es', NULL, CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'), @@ -23979,23 +23978,23 @@ BEGIN DECLARE vLastSenderInstructions VARCHAR(255); DECLARE vLastId INT; DECLARE vCurrentAgency INT; - + SELECT am.agencyFk INTO vCurrentAgency FROM vn.agencyMode am JOIN vn.ticket t ON t.agencyModeFk = am.id WHERE t.id = NEW.ticketFk; - + SELECT MAX(cmr.id) INTO vLastId FROM cmr JOIN vn.ticket t ON t.id = cmr.ticketFk JOIN vn.agencyMode am ON am.id = t.agencyModeFk - WHERE am.agencyFk = vCurrentAgency + WHERE am.agencyFk = vCurrentAgency ; - + SELECT senderInstruccions INTO vLastSenderInstructions FROM cmr WHERE id = vLastId; - + SET NEW.senderInstruccions = vLastSenderInstructions; END */;; @@ -24125,39 +24124,39 @@ CREATE TABLE `collection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` - BEFORE UPDATE ON `collection` - FOR EACH ROW -BEGIN - - DECLARE vStateFk INT; - DECLARE vTotalLines INT; - DECLARE vPickedLines INT; - - IF NEW.saleTotalCount <= NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount - OR NEW.salePickedCount != OLD.salePickedCount) - THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'PREPARED'; - - SET NEW.stateFk = vStateFk; - - END IF; - - IF NEW.saleTotalCount > NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'ON_PREPARATION'; - - SET NEW.stateFk = vStateFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` + BEFORE UPDATE ON `collection` + FOR EACH ROW +BEGIN + + DECLARE vStateFk INT; + DECLARE vTotalLines INT; + DECLARE vPickedLines INT; + + IF NEW.saleTotalCount <= NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount + OR NEW.salePickedCount != OLD.salePickedCount) + THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'PREPARED'; + + SET NEW.stateFk = vStateFk; + + END IF; + + IF NEW.saleTotalCount > NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'ON_PREPARATION'; + + SET NEW.stateFk = vStateFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -25042,7 +25041,7 @@ BEGIN UPDATE `client` c JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -25301,7 +25300,7 @@ BEGIN JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk WHERE b.departmentFk = OLD.id; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -25321,9 +25320,9 @@ DELIMITER ;; AFTER DELETE ON `department` FOR EACH ROW BEGIN - + UPDATE vn.department_recalc SET isChanged = TRUE; - + UPDATE vn.business b JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk @@ -25561,20 +25560,20 @@ DELIMITER ;; BEGIN DECLARE vHardCopyNumber INT; DECLARE vDmsTypeCode INT; - + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN CALL util.throw('this warehouse has not dms'); END IF; IF NEW.hasFile THEN - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms WHERE warehouseFk = NEW.warehouseFk; - + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); END IF; - - SELECT code INTO vDmsTypeCode + + SELECT code INTO vDmsTypeCode FROM dmsType WHERE NEW.dmsTypeFk = id; IF (vDmsTypeCode ='ticket') THEN UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference; @@ -25594,31 +25593,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` - BEFORE UPDATE ON `dms` - FOR EACH ROW -BEGIN - DECLARE vHardCopyNumber INT; - - IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) - OR - (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN - - IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN - SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); - END IF; - - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms - WHERE warehouseFk = NEW.warehouseFk; - - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); - END IF; - - IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN - - SET NEW.hasFile = 0; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` + BEFORE UPDATE ON `dms` + FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) + OR + (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN + + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN + SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); + END IF; + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -25637,14 +25636,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeDelete` BEFORE DELETE ON `dms` FOR EACH ROW -BEGIN +BEGIN DECLARE vCanNotBeDeleted INT; - SELECT COUNT(*) INTO vCanNotBeDeleted - FROM dmsType dt - WHERE NOT (code <=> 'trash') + SELECT COUNT(*) INTO vCanNotBeDeleted + FROM dmsType dt + WHERE NOT (code <=> 'trash') AND dt.id = OLD.dmsTypeFk; - - IF vCanNotBeDeleted THEN + + IF vCanNotBeDeleted THEN CALL util.throw('A dms can not be deleted'); END IF; END */;; @@ -26159,7 +26158,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterInsert` AFTER INSERT ON `entry` FOR EACH ROW -BEGIN +BEGIN CALL travel_requestRecalc(NEW.travelFk); END */;; DELIMITER ; @@ -26199,7 +26198,7 @@ BEGIN 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 @@ -26219,7 +26218,7 @@ BEGIN END IF; IF !(NEW.travelFk <=> OLD.travelFk) - OR !(NEW.currencyFk <=> OLD.currencyFk) THEN + OR !(NEW.currencyFk <=> OLD.currencyFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); END IF; @@ -26254,7 +26253,7 @@ BEGIN OR !(NEW.isRaid <=> OLD.isRaid) THEN CALL stock.log_add('entry', NEW.id, OLD.id); END IF; - + IF !(NEW.travelFk <=> OLD.travelFk) THEN CALL travel_requestRecalc(OLD.travelFk); CALL travel_requestRecalc(NEW.travelFk); @@ -26307,7 +26306,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`entry_afterDelete` AFTER DELETE ON `entry` FOR EACH ROW -BEGIN +BEGIN CALL travel_requestRecalc(OLD.travelFk); END */;; DELIMITER ; @@ -26656,17 +26655,17 @@ BEGIN DECLARE intcounter INT; DECLARE vShipFk INT; - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL 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 + 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) + 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 + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = intcounter; @@ -26691,9 +26690,9 @@ DELIMITER ;; FOR EACH ROW BEGIN IF NEW.counter <> OLD.counter THEN - IF (SELECT COUNT(*) FROM expedition e + IF (SELECT COUNT(*) FROM expedition e INNER JOIN ticket t1 ON e.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN SET NEW.id = NULL; END IF; @@ -26717,11 +26716,11 @@ DELIMITER ;; BEFORE DELETE ON `expedition` FOR EACH ROW BEGIN - UPDATE ticket t - SET packages = (SELECT COUNT(counter)-1 + UPDATE ticket t + SET packages = (SELECT COUNT(counter)-1 FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk) - WHERE t.id = OLD.ticketFk; - + WHERE t.id = OLD.ticketFk; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26835,13 +26834,13 @@ DELIMITER ;; BEGIN DECLARE vNewPosition INT; - + SELECT MAX(position) + 1 INTO vNewPosition FROM vn.expeditionPallet WHERE truckFk = NEW.truckFk; - + SET NEW.position = IFNULL(vNewPosition,1); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26940,7 +26939,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27001,9 +27000,9 @@ DELIMITER ;; BEFORE INSERT ON expeditionState FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27027,7 +27026,7 @@ BEGIN UPDATE vn.expedition e SET e.stateTypeFk = NEW.typeFk WHERE e.id = NEW.expeditionFk; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27852,49 +27851,49 @@ BEGIN DECLARE vIssuingCountry, vhostCountry INT; DECLARE vActive TINYINT; DECLARE vWithholdingSageFk INT; - - SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + + SELECT withholdingSageFk INTO vWithholdingSageFk + FROM vn.supplier WHERE id = NEW.supplierFk; - SET NEW.withholdingSageFk = vWithholdingSageFk; - - SELECT countryFk, isActive INTO vIssuingCountry, vActive - FROM vn.supplier + SET NEW.withholdingSageFk = vWithholdingSageFk; + + SELECT countryFk, isActive INTO vIssuingCountry, vActive + FROM vn.supplier WHERE id = NEW.supplierFk; - - SELECT countryFk INTO vhostCountry - FROM vn.supplier + + SELECT countryFk INTO vhostCountry + FROM vn.supplier WHERE id = NEW.companyFk; IF vActive = 0 THEN CALL util.throw('INACTIVE_PROVIDER'); END IF; - - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) ) THEN CALL util.throw('reference duplicated'); END IF; - + SELECT CASE WHEN (SELECT account FROM vn.supplier where id = NEW.supplierFk) LIKE '___3______' THEN 'C' - WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R' - WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' + WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' WHEN (SELECT vIssuingCountry<>vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' + where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' END INTO vSerie; - + SET NEW.serial = IFNULL(vSerie,'R'); IF vSerie LIKE 'W' THEN - SELECT IFNULL(MAX(serialNumber) + 1,1) INTO vNumReceived - FROM invoiceIn - WHERE `serial` LIKE NEW.serial AND - YEAR(issued) = YEAR(NEW.issued) AND + SELECT IFNULL(MAX(serialNumber) + 1,1) INTO vNumReceived + FROM invoiceIn + WHERE `serial` LIKE NEW.serial AND + YEAR(issued) = YEAR(NEW.issued) AND companyFk = NEW.companyFk; SET NEW.serialNumber = vNumReceived; END IF; @@ -27920,9 +27919,9 @@ BEGIN DECLARE vWithholdingSageFk INT; - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) AND id <> NEW.id ) THEN @@ -27932,7 +27931,7 @@ BEGIN IF NEW.supplierFk != OLD.supplierFk THEN CALL supplier_checkIsActive(NEW.supplierFk); SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + FROM vn.supplier WHERE id = NEW.supplierFk; SET NEW.withholdingSageFk = vWithholdingSageFk; END IF; @@ -27957,23 +27956,23 @@ DELIMITER ;; FOR EACH ROW BEGIN - IF NEW.issued != OLD.issued + IF NEW.issued != OLD.issued OR NEW.currencyFk != OLD.currencyFk THEN UPDATE invoiceInTax iit JOIN invoiceIn ii ON ii.id = iit.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value) WHERE ii.id = NEW.id; - + UPDATE invoiceInDueDay iidd JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value) - WHERE ii.id = NEW.id; - + WHERE ii.id = NEW.id; + END IF; END */;; @@ -28019,13 +28018,13 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vIsNotified BOOLEAN; - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -28033,12 +28032,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount, '€ en una fecha pasada en la recibida ', NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28059,13 +28058,13 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vIsNotified BOOLEAN; - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -28073,12 +28072,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount,'€ en una fecha pasada en la recibida ',NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28350,15 +28349,15 @@ DELIMITER ;; FOR EACH ROW BEGIN CALL clientRisk_update(NEW.clientFk, NEW.companyFk, NEW.amount); - IF (SELECT COUNT(*) - FROM client - WHERE id = NEW.clientFk + IF (SELECT COUNT(*) + FROM client + WHERE id = NEW.clientFk AND businessTypeFk = 'officialOrganism' ) THEN CALL mail_insert('administracion@verdnatura.es', NULL, CONCAT('Se ha emitido una factura al organismo: ', NEW.clientFk), - CONCAT('Presentar factura en FACE https://salix.verdnatura.es/#!/invoice-out/', + CONCAT('Presentar factura en FACE https://salix.verdnatura.es/#!/invoice-out/', NEW.id, '/summary')); END IF; @@ -28627,13 +28626,13 @@ BEGIN DECLARE vItemPackingType VARCHAR(1); IF NEW.itemPackingTypeFk IS NULL THEN - + SELECT itemPackingTypeFk INTO vItemPackingType - FROM vn.itemType it + FROM vn.itemType it WHERE id = NEW.typeFk; SET NEW.itemPackingTypeFk = vItemPackingType; - + END IF; END */;; DELIMITER ; @@ -28650,26 +28649,26 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` - AFTER INSERT ON `item` - FOR EACH ROW -BEGIN - - CALL hedera.image_ref('catalog', NEW.image); - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk) - SELECT NEW.id, 1; - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk) - SELECT NEW.id, 5; - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk) - SELECT NEW.id, 30; - - DELETE ifr.* - FROM edi.item_free ifr - WHERE ifr.id = NEW.id; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` + AFTER INSERT ON `item` + FOR EACH ROW +BEGIN + + CALL hedera.image_ref('catalog', NEW.image); + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 1; + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 5; + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 30; + + DELETE ifr.* + FROM edi.item_free ifr + WHERE ifr.id = NEW.id; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28689,23 +28688,23 @@ DELIMITER ;; BEFORE UPDATE ON `item` FOR EACH ROW BEGIN - + DECLARE vNewPackingShelve INT; - IF ISNULL(NEW.packingShelve) AND NOT ISNULL(NEW.packingOut) THEN - - SELECT NEW.packingOut * vc.shelveVolume / vc.standardFlowerBox + IF ISNULL(NEW.packingShelve) AND NOT ISNULL(NEW.packingOut) THEN + + SELECT NEW.packingOut * vc.shelveVolume / vc.standardFlowerBox INTO vNewPackingShelve FROM vn.volumeConfig vc; - + SET NEW.packingShelve = vNewPackingShelve; - + END IF; IF NEW.itemPackingTypeFk = '' THEN SET NEW.itemPackingTypeFk = NULL; - + END IF; END */;; @@ -29018,15 +29017,15 @@ BEGIN IF NEW.itemFk IN (95, 98) THEN SET NEW.cm3 = 0; END IF; - + IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.itemCost ic JOIN vn.sale s ON s.itemFk = ic.itemFk - JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk + JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND ic.itemFk = NEW.itemFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -29343,10 +29342,10 @@ DELIMITER ;; BEFORE INSERT ON `itemShelving` FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29453,8 +29452,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_DELETE` BEFORE DELETE ON `itemShelving` FOR EACH ROW -INSERT INTO vn.itemShelvingLog(itemShelvingFk, - workerFk, +INSERT INTO vn.itemShelvingLog(itemShelvingFk, + workerFk, accion, shelvingFk, itemFk) @@ -29636,7 +29635,7 @@ DELIMITER ;; BEGIN UPDATE vn.sale - SET isPicked = TRUE + SET isPicked = TRUE WHERE id = NEW.saleFk; END */;; @@ -29808,7 +29807,7 @@ trig: BEGIN IF @isTriggerDisabled OR visTriggerDisabled THEN LEAVE trig; END IF; - + SET vItemFk = NEW.itemFk; DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item @@ -29833,7 +29832,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate` BEFORE UPDATE ON `itemTag` FOR EACH ROW -BEGIN +BEGIN IF !(OLD.`value` <=> NEW.`value`) OR !(OLD.intValue <=> NEW.intValue) THEN SET NEW.intValue = itemTag_getIntValue(NEW.`value`); @@ -29866,7 +29865,7 @@ trig: BEGIN IF @isTriggerDisabled OR visTriggerDisabled THEN LEAVE trig; END IF; - + SET vItemFk = NEW.itemFk; DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item @@ -29902,7 +29901,7 @@ trig: BEGIN IF @isTriggerDisabled OR visTriggerDisabled THEN LEAVE trig; END IF; - + SET vItemFk = OLD.itemFk; DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item @@ -30310,7 +30309,7 @@ DELIMITER ;; BEFORE INSERT ON `machine` FOR EACH ROW BEGIN - + SET NEW.workerFk = vn.getUser(); END */;; @@ -30444,9 +30443,9 @@ DELIMITER ;; BEGIN IF NEW.sender IS NOT NULL THEN - + SET NEW.receiver = NEW.sender; - + END IF; END */;; @@ -30509,8 +30508,8 @@ DELIMITER ;; FOR EACH ROW BEGIN IF (NEW.code IS NULL) THEN - SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT - FROM information_schema.TABLES + SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT + FROM information_schema.TABLES WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate')); END IF; END */;; @@ -30988,13 +30987,15 @@ CREATE TABLE `osTicketConfig` ( `password` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `oldStatus` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `newStatusId` int(11) DEFAULT NULL, - `action` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `day` int(11) DEFAULT NULL, `comment` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `hostDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `userDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `passwordDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `portDb` int(11) DEFAULT NULL, + `responseType` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `fromEmailId` int(11) DEFAULT NULL, + `replyTo` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -31378,7 +31379,7 @@ DELIMITER ;; BEGIN -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31503,13 +31504,13 @@ BEGIN SELECT account INTO cuenta_banco FROM bank WHERE id = NEW.bankFk; - + SELECT account INTO cuenta_proveedor FROM supplier WHERE id = NEW.supplierFk; - + CALL vn.ledger_next(vNewBookEntry); - + INSERT INTO XDiario ( ASIEN, FECHA, SUBCTA, @@ -31535,7 +31536,7 @@ BEGIN cuenta_banco CONTRA, NEW.amount EURODEBE, 0 EUROHABER) gf; - + IF NEW.bankingFees <> 0 THEN INSERT INTO XDiario ( ASIEN, FECHA, @@ -31557,7 +31558,7 @@ BEGIN FROM supplier s JOIN country c ON s.countryFk = c.id WHERE s.id = NEW.supplierFk; - END IF; + END IF; END IF; SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); @@ -31565,15 +31566,15 @@ BEGIN SELECT isActive INTO isSupplierActive FROM supplier WHERE id = NEW.supplierFk; - + IF isSupplierActive = FALSE THEN CALL util.throw('SUPPLIER_INACTIVE'); END IF; - + IF ISNULL(NEW.workerFk) THEN SET NEW.workerFk = account.myUser_getId(); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31595,12 +31596,12 @@ DELIMITER ;; BEGIN DECLARE vIsPayMethodChecked BOOLEAN; DECLARE vEmail VARCHAR(150); - + SELECT isPayMethodChecked INTO vIsPayMethodChecked FROM supplier WHERE id = NEW.supplierFk; - - + + IF vIsPayMethodChecked = FALSE THEN SELECT notificationEmail INTO vEmail @@ -32465,11 +32466,11 @@ DELIMITER ;; BEFORE INSERT ON projectNotes FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -32625,10 +32626,10 @@ DELIMITER ;; BEFORE INSERT ON `province` FOR EACH ROW BEGIN - + SET NEW.geoFk = zoneGeo_new('province', NEW.`name`, (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END */;; @@ -32649,14 +32650,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate` BEFORE UPDATE ON `province` FOR EACH ROW -BEGIN - +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -32672,19 +32673,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` - AFTER UPDATE ON `province` - FOR EACH ROW -BEGIN - IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - END IF; - - IF !(OLD.`name` <=> NEW.`name`) THEN - UPDATE zoneGeo SET `name` = NEW.`name` - WHERE id = NEW.geoFk; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` + FOR EACH ROW +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -32704,7 +32705,7 @@ DELIMITER ;; AFTER DELETE ON `province` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -32833,20 +32834,20 @@ CREATE TABLE `receipt` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` - BEFORE INSERT ON `receipt` - FOR EACH ROW -BEGIN - DECLARE vIsAutoConciliated BOOLEAN; - - IF NEW.isConciliate = FALSE THEN - SELECT isAutoConciliated INTO vIsAutoConciliated - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; - - SET NEW.isConciliate = vIsAutoConciliated; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` + BEFORE INSERT ON `receipt` + FOR EACH ROW +BEGIN + DECLARE vIsAutoConciliated BOOLEAN; + + IF NEW.isConciliate = FALSE THEN + SELECT isAutoConciliated INTO vIsAutoConciliated + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; + + SET NEW.isConciliate = vIsAutoConciliated; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -32902,18 +32903,18 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` - AFTER UPDATE ON `receipt` - FOR EACH ROW -BEGIN - IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN - CALL mail_insert( - 'finanzas@verdnatura.es', - NULL, - CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), - CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` + AFTER UPDATE ON `receipt` + FOR EACH ROW +BEGIN + IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN + CALL mail_insert( + 'finanzas@verdnatura.es', + NULL, + CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), + CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33185,14 +33186,14 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vKmMax INT; - + IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN - SET NEW.m3 = ( SELECT SUM(litros)/1000 - FROM vn.saleVolume s - JOIN vn.ticket t ON s.ticketFk = t.id + SET NEW.m3 = ( SELECT SUM(litros)/1000 + FROM vn.saleVolume s + JOIN vn.ticket t ON s.ticketFk = t.id WHERE t.routeFk = NEW.id); END IF; - + IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN CALL util.throw ('KmEnd menor que kmStart'); END IF; @@ -33226,15 +33227,15 @@ BEGIN IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - + -- Inserta el gestdoc en todos los tickets de la ruta INSERT INTO ticketDms(ticketFk,dmsFk) SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; - -- Update del firmado - UPDATE ticket t - JOIN ticketDms tg ON t.id = tg.ticketFk + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk SET isSigned = 1 WHERE t.routeFk = NEW.id; END IF; @@ -33543,7 +33544,7 @@ DELIMITER ;; AFTER INSERT ON `sale` FOR EACH ROW BEGIN - + IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; @@ -33552,20 +33553,20 @@ BEGIN CALL ticket_requestRecalc(NEW.ticketFk); IF NEW.quantity > 0 THEN - + UPDATE vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk - JOIN vn.item i ON i.id = NEW.itemFk - AND (c.itemPackingTypeFk = i.itemPackingTypeFk + JOIN vn.item i ON i.id = NEW.itemFk + AND (c.itemPackingTypeFk = i.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) SET c.saleTotalCount = c.saleTotalCount + 1; - + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND s.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -33590,7 +33591,7 @@ DELIMITER ;; BEFORE UPDATE ON `sale` FOR EACH ROW BEGIN -/* +/* IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; @@ -33601,7 +33602,7 @@ BEGIN IF old.discount > 0 AND NEW.discount = 0 THEN INSERT INTO ticketLog - SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Cambio de descuento del item :', ' ', new.itemFk, ' de ', old.discount ,' a 0 '); END IF; END */;; @@ -33627,7 +33628,7 @@ BEGIN DECLARE vPickedLines INT; DECLARE vCollectionFk INT; DECLARE vUserRole VARCHAR(255); - + IF !(NEW.id <=> OLD.id) OR !(NEW.ticketFk <=> OLD.ticketFk) OR !(NEW.itemFk <=> OLD.itemFk) @@ -33650,64 +33651,64 @@ BEGIN UPDATE ticketRequest SET ticketFk = NEW.ticketFk WHERE saleFk = NEW.id; END IF; - + SELECT account.myUser_getName() INTO vUserRole; SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole; IF !(OLD.quantity <=> NEW.quantity) THEN - SELECT COUNT(*) INTO vIsToSendMail + SELECT COUNT(*) INTO vIsToSendMail FROM vncontrol.inter i JOIN vn.state s ON s.id = i.state_id - WHERE s.code='PACKED' + WHERE s.code='PACKED' AND i.Id_Ticket = OLD.ticketFk AND vUserRole IN ('salesPerson', 'salesTeamBoss') LIMIT 1; - - IF vIsToSendMail THEN + + IF vIsToSendMail THEN CALL vn.mail_insert('jefesventas@verdnatura.es', 'noreply@verdnatura.es', CONCAT('Ticket ', OLD.ticketFk ,' modificada cantidad tras encajado'), CONCAT('Ticket ', OLD.ticketFk ,'.
', - 'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity, + 'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity, ' del artículo ', OLD.itemFk, ' tras estado encajado del ticket.
', 'Este email se ha generado automáticamente' ) ); - END IF; + END IF; IF (OLD.quantity > NEW.quantity) THEN INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT NEW.id, cm.id, sc.value + SELECT NEW.id, cm.id, sc.value FROM saleComponent sc JOIN component cd ON cd.id = sc.componentFk JOIN component cm ON cm.code = 'mana' WHERE saleFk = NEW.id AND cd.code = 'lastUnitsDiscount' ON DUPLICATE KEY UPDATE value = sc.value + VALUES(value); - - DELETE sc.* + + DELETE sc.* FROM vn.saleComponent sc JOIN component c ON c.id = sc.componentFk WHERE saleFk = NEW.id AND c.code = 'lastUnitsDiscount'; - END IF; + END IF; INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND s.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; END IF; IF !(ABS(NEW.isPicked) <=> ABS(OLD.isPicked)) AND NEW.quantity > 0 THEN - + UPDATE vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk SET c.salePickedCount = c.salePickedCount + IF(NEW.isPicked != 0, 1, -1); - + END IF; IF !(NEW.quantity <=> OLD.quantity) AND (NEW.quantity = 0 OR OLD.quantity = 0) THEN - + UPDATE vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk SET c.saleTotalCount = c.saleTotalCount + IF(OLD.quantity = 0, 1, -1); @@ -33733,11 +33734,11 @@ DELIMITER ;; BEGIN IF OLD.quantity > 0 THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND s.id = OLD.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -33760,43 +33761,43 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`sale_afterDelete` AFTER DELETE ON `sale` FOR EACH ROW -BEGIN +BEGIN DECLARE vIsToSendMail BOOL; DECLARE vUserRole VARCHAR(255); - + CALL stock.log_add('sale', NULL, OLD.id); CALL ticket_requestRecalc(OLD.ticketFk); SELECT account.myUser_getName() INTO vUserRole; SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole; - SELECT COUNT(*) INTO vIsToSendMail + SELECT COUNT(*) INTO vIsToSendMail FROM vncontrol.inter i JOIN vn.state s ON s.id = i.state_id - WHERE s.code='PACKED' + WHERE s.code='PACKED' AND i.Id_Ticket = OLD.ticketFk AND vUserRole IN ('salesPerson', 'salesBoss') LIMIT 1; - IF vIsToSendMail THEN + IF vIsToSendMail THEN CALL vn.mail_insert('jefesventas@verdnatura.es', 'noreply@verdnatura.es', CONCAT('Ticket ', OLD.ticketFk ,' eliminado artículo tras encajado' ), CONCAT('Ticket ', OLD.ticketFk ,'.
', 'Eliminado artículo ', OLD.itemFk, ' tras estado encajado del ticket.
Este email se ha generado automáticamente' ) ); - END IF; - + END IF; + IF OLD.quantity > 0 THEN - + UPDATE vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = OLD.ticketFk - JOIN vn.item i ON i.id = OLD.itemFk - AND (c.itemPackingTypeFk = i.itemPackingTypeFk + JOIN vn.item i ON i.id = OLD.itemFk + AND (c.itemPackingTypeFk = i.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) SET c.saleTotalCount = c.saleTotalCount - 1, c.salePickedCount = c.salePickedCount - ABS(OLD.isPicked); - + END IF; END */;; DELIMITER ; @@ -33835,10 +33836,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`BEFORE_INSERT` BEFORE INSERT ON `saleBuy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33857,13 +33858,13 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleBuy_AI` AFTER INSERT ON `saleBuy` FOR EACH ROW -BEGIN +BEGIN /* Activar de nuevo cuando volvamos a vender fruta y verdura - * + * UPDATE vn.sale s SET s.concept = CONCAT(s.concept, ' Lote: ', NEW.buyFk) WHERE s.id = NEW.saleFk; -*/ +*/ END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34169,14 +34170,14 @@ DELIMITER ;; AFTER INSERT ON `saleTracking` FOR EACH ROW BEGIN - - IF NEW.isChecked THEN - + + IF NEW.isChecked THEN + UPDATE vn.sale s - SET s.isPicked = TRUE + SET s.isPicked = TRUE WHERE s.id = NEW.saleFk AND s.isPicked = 0; - + END IF; END */;; @@ -34485,9 +34486,9 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; END */;; @@ -34512,14 +34513,14 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; - - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; @@ -34542,9 +34543,9 @@ DELIMITER ;; BEFORE DELETE ON `sharingCart` FOR EACH ROW BEGIN - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; END */;; DELIMITER ; @@ -34677,9 +34678,9 @@ DELIMITER ;; BEGIN IF NEW.code = "" THEN - + CALL util.throw('NOT_EMPTY_CODE_ALLOWED'); - + END IF; END */;; @@ -34701,13 +34702,13 @@ DELIMITER ;; BEFORE UPDATE ON `shelving` FOR EACH ROW BEGIN - + IF NEW.code = "" THEN - + CALL util.throw('NOT_EMPTY_CODE_ALLOWED'); - + END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34899,7 +34900,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; END */;; @@ -34923,12 +34924,12 @@ DELIMITER ;; BEGIN IF NEW.dateLeaving IS NOT NULL THEN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; ELSE UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; END IF; @@ -34952,7 +34953,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; END */;; @@ -35306,7 +35307,7 @@ BEGIN IF vPayMethodHasVerified AND !vHasChange THEN SET vHasChange = (NEW.payMethodFk <> OLD.payMethodFk); END IF; - + IF vHasChange THEN SET NEW.isPayMethodChecked = FALSE; END IF; @@ -35375,23 +35376,23 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER supplierAccount_afterUpdate - AFTER UPDATE ON supplierAccount - FOR EACH ROW -BEGIN - DECLARE vPayMethodHasVerified BOOL; - - SELECT pm.hasVerified INTO vPayMethodHasVerified - FROM vn.supplier s - JOIN vn.payMethod pm ON pm.id = s.payMethodFk - WHERE s.id = OLD.supplierFk; - - IF OLD.iban <> NEW.iban OR OLD.bankEntityFk <> NEW.bankEntityFk AND vPayMethodHasVerified THEN - UPDATE vn.supplier - SET isPayMethodChecked = FALSE - WHERE id = OLD.supplierFk; - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER supplierAccount_afterUpdate + AFTER UPDATE ON supplierAccount + FOR EACH ROW +BEGIN + DECLARE vPayMethodHasVerified BOOL; + + SELECT pm.hasVerified INTO vPayMethodHasVerified + FROM vn.supplier s + JOIN vn.payMethod pm ON pm.id = s.payMethodFk + WHERE s.id = OLD.supplierFk; + + IF OLD.iban <> NEW.iban OR OLD.bankEntityFk <> NEW.bankEntityFk AND vPayMethodHasVerified THEN + UPDATE vn.supplier + SET isPayMethodChecked = FALSE + WHERE id = OLD.supplierFk; + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35913,11 +35914,11 @@ DELIMITER ;; AFTER INSERT ON `ticket` FOR EACH ROW BEGIN - + DECLARE vClientType VARCHAR(255); DECLARE vStateCode VARCHAR(255); DECLARE vTransferorFirstShipped DATE; - + -- Borrar cuando se cambie el insert ticket en la APP móvil SELECT typeFk INTO vClientType @@ -35930,8 +35931,8 @@ BEGIN END IF; INSERT INTO vncontrol.inter(Id_Ticket, state_id, Id_Trabajador) - SELECT NEW.id, id, account.myUser_getId() - FROM state + SELECT NEW.id, id, account.myUser_getId() + FROM state WHERE `code` = vStateCode COLLATE utf8_general_ci; IF YEAR(NEW.shipped) > 2000 THEN @@ -35944,7 +35945,7 @@ BEGIN INSERT INTO bs.clientNewBorn(clientFk, firstShipped, lastShipped) VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, util.VN_CURDATE()), util.VN_CURDATE()) ON DUPLICATE KEY UPDATE lastShipped = util.VN_CURDATE(); - + END IF; END */;; @@ -35967,17 +35968,17 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vNewTime TIME; - + IF !(NEW.routeFk <=> OLD.routeFk) THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id IN (OLD.routeFk,NEW.routeFk) AND r.created >= util.VN_CURDATE() GROUP BY r.id; END IF; - + IF !(DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN IF YEAR(NEW.shipped) < 2000 THEN SIGNAL SQLSTATE '46000' @@ -35989,13 +35990,13 @@ BEGIN END IF; END IF; - + IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.ticket t JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND t.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -36005,7 +36006,7 @@ BEGIN SET NEW.zoneFk = NULL; END IF; - IF NEW.routeFk AND NEW.isDeleted THEN + IF NEW.routeFk AND NEW.isDeleted THEN CALL util.throw ('This ticket is deleted'); END IF; @@ -36014,22 +36015,22 @@ BEGIN FROM vn.ticket WHERE routeFk = NEW.routeFk HAVING MAX(TIME(shipped)) > TIME(NEW.shipped); - + IF vNewTime THEN SET NEW.shipped = TIMESTAMP(DATE(NEW.shipped), vNewTime); INSERT INTO vn.ticketLog - SET originFk = NEW.id, - userFk = account.myUser_getId(), - `action` = 'update', + SET originFk = NEW.id, + userFk = account.myUser_getId(), + `action` = 'update', description = CONCAT('Cambia la hora por cambio de ruta de ', TIME(OLD.shipped), ' a ', TIME(NEW.shipped)); END IF; INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk) - SELECT r.agencyModeFk, NEW.zoneFk FROM route r + SELECT r.agencyModeFk, NEW.zoneFk FROM route r WHERE r.id = NEW.routeFk; - + CALL vn.routeUpdateM3(NEW.routeFk); END IF; END */;; @@ -36063,7 +36064,7 @@ BEGIN OR !(NEW.companyFk <=> OLD.companyFk) THEN CALL ticket_requestRecalc(NEW.id); END IF; - + IF NEW.clientFk = 2067 AND !(NEW.clientFk <=> OLD.clientFk) THEN -- Fallo que se insertan no se sabe como tickets en este cliente CALL mail_insert( @@ -36073,10 +36074,10 @@ BEGIN CONCAT(account.myUser_getName(), ' ha modificado el ticket ',NEW.id) ); END IF; - + IF NEW.routeFk <> OLD.routeFk THEN - UPDATE expedition + UPDATE expedition SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; @@ -36100,11 +36101,11 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeDelete` BEFORE DELETE ON `ticket` FOR EACH ROW -BEGIN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id +BEGIN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id = OLD.routeFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -36157,31 +36158,31 @@ CREATE TABLE `ticketCollection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete -AFTER DELETE -ON ticketCollection FOR EACH ROW -BEGIN - - DECLARE vSalesRemaining INT; - - SELECT count(*) INTO vSalesRemaining - FROM vn.ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE collectionFk = OLD.collectionFk - AND tc.id != OLD.id; - - IF NOT vSalesRemaining THEN - - DELETE FROM vn.collection WHERE id = OLD.collectionFk; - - ELSE - - UPDATE vn.collection - SET saleTotalCount = vSalesRemaining - WHERE id = OLD.collectionFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete +AFTER DELETE +ON ticketCollection FOR EACH ROW +BEGIN + + DECLARE vSalesRemaining INT; + + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + WHERE collectionFk = OLD.collectionFk + AND tc.id != OLD.id; + + IF NOT vSalesRemaining THEN + + DELETE FROM vn.collection WHERE id = OLD.collectionFk; + + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36233,13 +36234,13 @@ DELIMITER ;; BEFORE DELETE ON `ticketDms` FOR EACH ROW BEGIN - UPDATE dms - SET dmsTypeFk = (SELECT id - FROM dmsType + UPDATE dms + SET dmsTypeFk = (SELECT id + FROM dmsType WHERE `code` = 'trash' ) - WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) - FROM ticketDms + WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) + FROM ticketDms WHERE dmsFk = OLD.dmsFk ) ; END */;; @@ -36303,6 +36304,9 @@ CREATE TABLE `ticketDown_SelectionType` ( -- Table structure for table `ticketLastState` -- +/ + + DROP TABLE IF EXISTS `ticketLastState`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; @@ -36590,7 +36594,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36835,7 +36839,7 @@ DELIMITER ;; BEGIN CALL ticket_requestRecalc(NEW.ticketFk); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36992,18 +36996,18 @@ BEGIN DECLARE vState VARCHAR(15); DECLARE vZoneFk INT; DECLARE vBoardingStateFk INT; - + SELECT s.code INTO vState FROM state s WHERE s.id = NEW.stateFk; - + SELECT t.zonefk INTO vZoneFk FROM ticket t - WHERE t.id = NEW.ticketFk; - + WHERE t.id = NEW.ticketFk; + IF vState = 'OK' AND vZoneFk IS NULL THEN CALL util.throw("ASSIGN_ZONE_FIRST"); - END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37024,11 +37028,11 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vNumTicketsPrepared INT; - + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state - WHERE id = NEW.stateFk; + WHERE id = NEW.stateFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37051,21 +37055,21 @@ BEGIN DECLARE vTicketFk INT; DECLARE vTicketTrackingFk INT; DECLARE vStateName VARCHAR(15); - + IF NEW.stateFk <> OLD.stateFk THEN REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state WHERE id = NEW.stateFk; END IF; - + IF NEW.ticketFk <> OLD.ticketFk THEN SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = NEW.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = NEW.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -37101,18 +37105,18 @@ BEGIN DELETE FROM vn.ticketLastState WHERE ticketFk = OLD.ticketFk; END; - + CALL util.debugAdd('deletedState', CONCAT('interFk: ', OLD.id, ' ticketFk: ', OLD.ticketFk, ' stateFk: ', OLD.stateFk)); SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = OLD.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = OLD.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -37692,7 +37696,7 @@ BEGIN CALL stock.log_add('travel', NEW.id, OLD.id); IF !(NEW.shipped <=> OLD.shipped) THEN - UPDATE entry + UPDATE entry SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) WHERE travelFk = NEW.id; END IF; @@ -38186,7 +38190,7 @@ DELIMITER ;; BEGIN IF NEW.isFeedStock THEN INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`); - INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) + INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) VALUES(NEW.id,LAST_INSERT_ID()); END IF; END */;; @@ -38210,7 +38214,7 @@ DELIMITER ;; BEGIN IF NEW.isFeedStock IS TRUE and OLD.isFeedStock IS FALSE then INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`); - INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) + INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) VALUES(NEW.id,LAST_INSERT_ID()); END IF; END */;; @@ -38922,9 +38926,9 @@ DELIMITER ;; AFTER INSERT ON `workerTimeControl` FOR EACH ROW BEGIN - IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN + IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN CALL util.throw('date in the future'); - END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39478,10 +39482,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BI` BEFORE INSERT ON `zoneExclusion` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39500,10 +39504,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BU` BEFORE UPDATE ON `zoneExclusion` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39753,28 +39757,28 @@ DELIMITER ;; DECLARE vIsAlreadyNotified BOOLEAN; DECLARE vNotificationThrehold INT; - SELECT actualNumber, endRange, isAlreadyNotified, notificationThrehold + SELECT actualNumber, endRange, isAlreadyNotified, notificationThrehold INTO vActualNumber, vEndRange, vIsAlreadyNotified, vNotificationThrehold FROM envialiaConfig; - + IF (vActualNumber+vNotificationThrehold) >= vEndRange AND vIsAlreadyNotified = FALSE THEN - CALL mail_insert( + CALL mail_insert( 'cau@verdnatura.es', NULL, 'Hablar con envialia, acercandonos al numero final del rango permitido para las etiquetas', CONCAT('Numero actual: ', vActualNumber, ' , numero final: ',vEndRange) - ); + ); UPDATE envialiaConfig SET isAlreadyNotified = TRUE; END IF; - + IF (vActualNumber+vNotificationThrehold) < vEndRange AND vIsAlreadyNotified = TRUE THEN UPDATE envialiaConfig SET isAlreadyNotified = FALSE; END IF; - + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -39821,7 +39825,7 @@ DELIMITER ;; DECLARE vDone BOOL DEFAULT FALSE; DECLARE vPrintQueueLimit INT; - DECLARE vCur CURSOR FOR + DECLARE vCur CURSOR FOR SELECT CONCAT(' ', IFNULL(pq.id, ''), ' ', IFNULL(p.path, ''),' @@ -39834,21 +39838,21 @@ DELIMITER ;; LEFT JOIN worker w ON w.id = pq.workerFk LEFT JOIN printer p ON p.id = pq.printerFk LEFT JOIN report r ON r.id = pq.reportFk - JOIN printQueueConfig + JOIN printQueueConfig LIMIT vPrintQueueLimit; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - SELECT printQueueLimit INTO vPrintQueueLimit + SELECT printQueueLimit INTO vPrintQueueLimit FROM printQueueConfig; SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum FROM printQueue WHERE statusCode = 'queued'; - SELECT isAlreadyNotified INTO vIsAlreadyNotified + SELECT isAlreadyNotified INTO vIsAlreadyNotified FROM printingQueueCheck; - + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND vIsAlreadyNotified = FALSE AND vCurrentCount > 0 @@ -39863,11 +39867,11 @@ DELIMITER ;; Trabajador Error ' INTO vTableQueue; - + OPEN vCur; l: LOOP - + SET vDone = FALSE; FETCH vCur INTO vLineQueue; @@ -39877,7 +39881,7 @@ DELIMITER ;; END IF; SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - + END LOOP; CLOSE vCur; @@ -39885,11 +39889,11 @@ DELIMITER ;; CALL mail_insert( 'cau@verdnatura.es', NULL, - 'Servidor de impresion parado', + 'Servidor de impresion parado', CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '') ); - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; END IF; IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND @@ -39901,7 +39905,7 @@ DELIMITER ;; UPDATE printingQueueCheck SET lastCount = vCurrentCount, lastCheckSum = vCheckSum; - + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -40010,16 +40014,16 @@ DELIMITER ;; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerTimeControl_sendMail` ON SCHEDULE EVERY 1 WEEK STARTS '2020-11-25 08:00:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN - DECLARE vWeek,vYear INT; - - SELECT week,year INTO vWeek,vYear - FROM vn.time - WHERE dated IN (DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL -4 DAY)) - GROUP BY year,week - LIMIT 1; - - CALL vn.workerTimeControl_sendMail(vWeek, vYear, NULL); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerTimeControl_sendMail` ON SCHEDULE EVERY 1 WEEK STARTS '2020-11-25 08:00:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN + DECLARE vWeek,vYear INT; + + SELECT week,year INTO vWeek,vYear + FROM vn.time + WHERE dated IN (DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL -4 DAY)) + GROUP BY year,week + LIMIT 1; + + CALL vn.workerTimeControl_sendMail(vWeek, vYear, NULL); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -40131,7 +40135,7 @@ BEGIN DECLARE vGeoFk INT; SELECT p.geoFk INTO vGeoFk - FROM address a + 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 @@ -40158,12 +40162,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11) DETERMINISTIC BEGIN - + /** * Obtiene el id del artículo * * @param vBarcode código de barras - * + * * return id del item */ @@ -40173,35 +40177,35 @@ BEGIN FROM vn.item WHERE id = vBarcode OR comment = vBarcode LIMIT 1; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT itemFk INTO vItemFk - FROM buy + SELECT itemFk INTO vItemFk + FROM buy WHERE id = vBarcode; - - IF vItemFk THEN - RETURN vItemFk; - END IF; - - SELECT itemFk INTO vItemFk - FROM itemBarcode - WHERE code = vBarcode; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT i.id INTO vItemFk + SELECT itemFk INTO vItemFk + FROM itemBarcode + WHERE code = vBarcode; + + IF vItemFk THEN + RETURN vItemFk; + END IF; + + SELECT i.id INTO vItemFk FROM vn.item i WHERE i.name LIKE CONCAT('%',vBarcode,'%') ORDER BY i.id ASC LIMIT 1; - + RETURN vItemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40223,9 +40227,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenus DETERMINISTIC BEGIN DECLARE vIsUpdatable INTEGER; - SELECT COUNT(*) INTO vIsUpdatable - FROM botanicExport - WHERE ediGenusFk = vEdiGenusFk + SELECT COUNT(*) INTO vIsUpdatable + FROM botanicExport + WHERE ediGenusFk = vEdiGenusFk AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL) AND (vCountryFk = countryFk OR IFNULL(vCountryFk,countryFk) IS NULL) AND vRestriction = restriction; @@ -40322,16 +40326,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `catalog_componentReverse`(vWarehouse DETERMINISTIC BEGIN /* Calcula los componentes para un cliente a partir de un coste y volumen - * @param vWarehouse + * @param vWarehouse * @param vCost Valor de coste del articulo * @param vM3 m3 del articulo - * @param vAddressFk + * @param vAddressFk * @param vZoneFk - * @return vRetailedPrice precio de venta sin iva + * @return vRetailedPrice precio de venta sin iva * @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) */ - - DECLARE vBoxVolume BIGINT; + + DECLARE vBoxVolume BIGINT; DECLARE vCustomer INT; DECLARE vComponentRecovery INT DEFAULT 17; DECLARE vComponentMana INT DEFAULT 39; @@ -40340,11 +40344,11 @@ BEGIN DECLARE vComponentCost INT DEFAULT 28; DECLARE vRetailedPrice DECIMAL(10,2); DECLARE vItem INT DEFAULT 98; - + SELECT volume INTO vBoxVolume FROM vn.packaging WHERE id = '94'; - + SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk; DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component; @@ -40368,7 +40372,7 @@ BEGIN -- Margen -- No se aplica margen, cau 12589 /* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost + SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost FROM vn.rate WHERE dated <= util.VN_CURDATE() AND warehouseFk = vWarehouse @@ -40377,7 +40381,7 @@ BEGIN */ -- Recobro INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) + SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) FROM bi.claims_ratio WHERE Id_Cliente = vCustomer AND recobro > 0.009; @@ -40394,7 +40398,7 @@ BEGIN ROUND( vM3 * (z.price - z.bonus) - * z.inflation + * z.inflation / vBoxVolume, 4 ) FROM zone z @@ -40423,20 +40427,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `clientGetDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return client risk - */ - - DECLARE vDebt DECIMAL(10,2); - - SELECT vn.client_getDebt(vClient,vDate) INTO vDebt; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return client risk + */ + + DECLARE vDebt DECIMAL(10,2); + + SELECT vn.client_getDebt(vClient,vDate) INTO vDebt; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40469,30 +40473,30 @@ BEGIN 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 + FROM ( SELECT mana FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated + AND dated = vFromDated UNION ALL SELECT s.quantity * value FROM ticket t @@ -40500,7 +40504,7 @@ BEGIN 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 > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE()) AND a.clientFk = vClient UNION ALL @@ -40564,7 +40568,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompa READS SQL DATA BEGIN /** - * Devuelve el area de un cliente, + * Devuelve el area de un cliente, * intracomunitario, extracomunitario o nacional. * * @param vClient Id del cliente @@ -40611,7 +40615,7 @@ BEGIN SELECT COUNT(*) INTO vHasDebt FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasDebt THEN RETURN 0; END IF; @@ -40699,8 +40703,8 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPerson`(vClientFk INT DETERMINISTIC BEGIN /** - * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo - * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de + * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo + * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de * sharingcart y tercero la de clientes. * * @param vClientFk El id del cliente @@ -40738,29 +40742,29 @@ BEGIN l: LOOP SELECT workerSubstitute INTO vWorkerSubstituteFk - FROM sharingCart + FROM sharingCart WHERE util.VN_CURDATE() BETWEEN started AND ended AND workerFk = vSalesPersonFk ORDER BY id LIMIT 1; - + IF vWorkerSubstituteFk IS NULL THEN LEAVE l; END IF; - + SELECT COUNT(*) > 0 INTO vLoop FROM tmp.stack WHERE substitute = vWorkerSubstituteFk; IF vLoop THEN LEAVE l; END IF; - + INSERT INTO tmp.stack SET substitute = vWorkerSubstituteFk; - + SET vSalesPersonFk = vWorkerSubstituteFk; END LOOP; - + DROP TEMPORARY TABLE tmp.stack; END IF; @@ -40794,11 +40798,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPerson(vClientFk, vDated); END ;; DELIMITER ; @@ -40829,12 +40833,12 @@ BEGIN **/ DECLARE vWorkerCode CHAR(3); DECLARE vSalesPersonFk INT; - + SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated); SELECT code INTO vWorkerCode - FROM worker + FROM worker WHERE id = vSalesPersonFk; RETURN vWorkerCode; @@ -40867,11 +40871,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPersonCode(vClientFk, vDated); END ;; DELIMITER ; @@ -40964,7 +40968,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated BEGIN DECLARE curRate DECIMAL(10,4); - + SELECT value INTO curRate FROM referenceRate WHERE dated <= vDated @@ -40995,23 +40999,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`( BEGIN /* * Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil - * + * * */ - + /*DECLARE vIsGranted BOOLEAN; DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; - SELECT dp.id INTO vDeviceProductionFk - FROM vn.deviceProduction dp + SELECT dp.id INTO vDeviceProductionFk + FROM vn.deviceProduction dp WHERE dp.android_id = android_id; IF vDeviceProductionFk THEN - - SELECT COUNT(*) INTO vIsGranted - FROM vn.deviceProductionUser dpu - WHERE dpu.userFk = vUserFK + + SELECT COUNT(*) INTO vIsGranted + FROM vn.deviceProductionUser dpu + WHERE dpu.userFk = vUserFK AND dpu.deviceProductionFk = vDeviceProductionFk; - + RETURN vIsGranted; END IF;*/ RETURN TRUE; @@ -41035,16 +41039,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass DETERMINISTIC BEGIN DECLARE vCountryFk INTEGER; - + SELECT s.countryFk INTO vCountryFk FROM dua d JOIN supplier s ON s.id = d.companyFk WHERE d.id = vDua; - + RETURN (SELECT rate FROM (SELECT taxClassFk, rate - FROM invoiceInTaxBookingAccount + FROM invoiceInTaxBookingAccount WHERE effectived <= util.VN_CURDATE() AND countryFk = vCountryFk AND taxClassFk = vTaxClass @@ -41070,70 +41074,70 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS int(11) READS SQL DATA -BEGIN -/** - * Devuelve el numero de entrada para el ekt - * - * @param vEktFk Identificador de edi.ekt - */ - DECLARE vTravelFk INT; - DECLARE vEntryFk INT DEFAULT 0; - DECLARE vEntryAssignFk INT; - - SELECT ea.id - INTO vEntryAssignFk - FROM edi.ekt e - JOIN vn.ektEntryAssign ea ON - IFNULL(ea.sub, e.sub) <=> e.sub AND - IFNULL(ea.kop, e.kop) <=> e.kop AND - IFNULL(ea.pro, e.pro) <=> e.pro AND - IFNULL(ea.auction, e.auction) <=> e.auction - WHERE e.id = vEktFk - ORDER BY - IF(ea.sub,1,0) * 1000 + - IF(ea.kop,1,0) * 100 + - IF(ea.pro,1,0) * 10 + - IF(ea.auction,1,0) DESC - LIMIT 1; - - SET vTravelFk = vn.ekt_getTravel(vEntryAssignFk, vEktFk); - - IF vTravelFk THEN - - SELECT MAX(e.id) - INTO vEntryFk - FROM vn.entry e - JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk - WHERE e.travelFk = vTravelFk - AND e.sub <=> ea.sub - AND e.kop <=> ea.kop - AND e.pro <=> ea.pro - AND e.auction <=> ea.auction - AND e.companyFk <=> ea.companyFk; - - IF vEntryFk IS NULL THEN - INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, ref, pro, auction) - SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction - FROM vn.ektEntryAssign ea - JOIN vn.currency cu ON cu.code = 'EUR' - WHERE ea.id = vEntryAssignFk; - - SET vEntryFk = LAST_INSERT_ID(); - END IF; - - UPDATE vn.ektEntryAssign - SET entryFk = vEntryFk - WHERE id = vEntryAssignFk; - - ELSE - - SELECT ec.defaultEntry INTO vEntryFk - FROM vn.entryConfig ec; - - INSERT IGNORE INTO vn.entry(id) VALUES(vEntryFk); - END IF; - - RETURN vEntryFk; +BEGIN +/** + * Devuelve el numero de entrada para el ekt + * + * @param vEktFk Identificador de edi.ekt + */ + DECLARE vTravelFk INT; + DECLARE vEntryFk INT DEFAULT 0; + DECLARE vEntryAssignFk INT; + + SELECT ea.id + INTO vEntryAssignFk + FROM edi.ekt e + JOIN vn.ektEntryAssign ea ON + IFNULL(ea.sub, e.sub) <=> e.sub AND + IFNULL(ea.kop, e.kop) <=> e.kop AND + IFNULL(ea.pro, e.pro) <=> e.pro AND + IFNULL(ea.auction, e.auction) <=> e.auction + WHERE e.id = vEktFk + ORDER BY + IF(ea.sub,1,0) * 1000 + + IF(ea.kop,1,0) * 100 + + IF(ea.pro,1,0) * 10 + + IF(ea.auction,1,0) DESC + LIMIT 1; + + SET vTravelFk = vn.ekt_getTravel(vEntryAssignFk, vEktFk); + + IF vTravelFk THEN + + SELECT MAX(e.id) + INTO vEntryFk + FROM vn.entry e + JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk + WHERE e.travelFk = vTravelFk + AND e.sub <=> ea.sub + AND e.kop <=> ea.kop + AND e.pro <=> ea.pro + AND e.auction <=> ea.auction + AND e.companyFk <=> ea.companyFk; + + IF vEntryFk IS NULL THEN + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, ref, pro, auction) + SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction + FROM vn.ektEntryAssign ea + JOIN vn.currency cu ON cu.code = 'EUR' + WHERE ea.id = vEntryAssignFk; + + SET vEntryFk = LAST_INSERT_ID(); + END IF; + + UPDATE vn.ektEntryAssign + SET entryFk = vEntryFk + WHERE id = vEntryAssignFk; + + ELSE + + SELECT ec.defaultEntry INTO vEntryFk + FROM vn.entryConfig ec; + + INSERT IGNORE INTO vn.entry(id) VALUES(vEntryFk); + END IF; + + RETURN vEntryFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41155,7 +41159,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, v BEGIN /** * Devuelve un vn.travel.id - * + * * @param vEntryAssignFk Identificador de vn.entryAssign */ DECLARE vTravelFk INT; @@ -41217,36 +41221,36 @@ BEGIN DECLARE vCurrentCommission INT; DECLARE vIsCurrencyUsd INT; DECLARE vLastEntryFk INT; - + SELECT count(*) INTO vIsCurrencyUsd FROM currency c WHERE c.code = 'USD' AND id = vCurrencyFk; - + IF NOT vIsCurrencyUsd THEN - + SELECT e.id INTO vLastEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk WHERE e.supplierFk = vSupplierFk ORDER BY tr.landed DESC LIMIT 1; - + IF vLastEntryFk THEN - + SELECT commission INTO vCurrentCommission FROM vn.entry WHERE id = vLastEntryFk; - + ELSE - + SELECT commission INTO vCurrentCommission FROM supplier s WHERE s.id = vSupplierFk; - + END IF; - + RETURN vCurrentCommission; - + ELSE SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission @@ -41255,11 +41259,11 @@ BEGIN 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 */ ; @@ -41311,10 +41315,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve una entrada para Logiflora. Si no existe la crea. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -41322,51 +41326,51 @@ BEGIN DECLARE vTravelFk INT; DECLARE vEntryFk INT; DECLARE previousEntryFk INT; - + SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk); - + IF vLanded THEN - - SELECT IFNULL(MAX(id),0) INTO vEntryFk + + SELECT IFNULL(MAX(id),0) INTO vEntryFk FROM vn.entry - WHERE travelFk = vTravelFk + WHERE travelFk = vTravelFk AND isRaid; IF NOT vEntryFk THEN - + INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid) SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE FROM vn.supplier s JOIN vn.company c ON c.code = 'VNL' JOIN vn.currency cu ON cu.code = 'EUR' WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - - END IF; - - END IF; - SELECT entryFk INTO previousEntryFk + END IF; + + END IF; + + SELECT entryFk INTO previousEntryFk FROM edi.warehouseFloramondo wf WHERE wf.warehouseFk = vWarehouseFk; - + IF IFNULL(previousEntryFk,0) != vEntryFk THEN - - UPDATE buy b - SET b.printedStickers = 0 + + UPDATE buy b + SET b.printedStickers = 0 WHERE entryFk = previousEntryFk; DELETE FROM buy WHERE entryFk = previousEntryFk; - + DELETE FROM entry WHERE id = previousEntryFk; - + END IF; - + RETURN vEntryFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41415,32 +41419,32 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_checkRoute`(vPalletFk INT,vExpeditionFk INT) RETURNS tinyint(1) DETERMINISTIC -BEGIN -/** -* Comprueba si las expediciones del pallet son todas -* de la misma ruta. -* -* @param vExpeditionFk numero de expedition a comprobar -* @param vPalletFk numero de pallet -* @return vHasDistinctRoutes -*/ - DECLARE vRouteFk INT; - DECLARE vHasDistinctRoutes BOOL; - - SELECT t.routeFk INTO vRouteFk - FROM vn.expedition e - JOIN vn.ticket t ON e.ticketFk = t.id - WHERE e.id = vExpeditionFk; - - SELECT COUNT(*) > 0 INTO vHasDistinctRoutes - FROM vn.expeditionScan es - JOIN vn.expedition e ON es.expeditionFk = e.id - JOIN vn.ticket t ON e.ticketFk = t.id - WHERE es.palletFk = vPalletFk - AND t.routeFk <> vRouteFk; - - RETURN vHasDistinctRoutes; - +BEGIN +/** +* Comprueba si las expediciones del pallet son todas +* de la misma ruta. +* +* @param vExpeditionFk numero de expedition a comprobar +* @param vPalletFk numero de pallet +* @return vHasDistinctRoutes +*/ + DECLARE vRouteFk INT; + DECLARE vHasDistinctRoutes BOOL; + + SELECT t.routeFk INTO vRouteFk + FROM vn.expedition e + JOIN vn.ticket t ON e.ticketFk = t.id + WHERE e.id = vExpeditionFk; + + SELECT COUNT(*) > 0 INTO vHasDistinctRoutes + FROM vn.expeditionScan es + JOIN vn.expedition e ON es.expeditionFk = e.id + JOIN vn.ticket t ON e.ticketFk = t.id + WHERE es.palletFk = vPalletFk + AND t.routeFk <> vRouteFk; + + RETURN vHasDistinctRoutes; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41499,27 +41503,27 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - + SELECT am.deliveryMethodFk - INTO vDeliveryType + INTO vDeliveryType FROM ticket t JOIN agencyMode am ON am.id = t.agencyModeFk WHERE t.id = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp - FROM ticket t + FROM ticket t LEFT JOIN warehouse w ON w.pickUpagencyModeFk = t.agencyModeFk WHERE t.id = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -41549,28 +41553,28 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - - SELECT + + SELECT a.Vista - INTO vDeliveryType + INTO vDeliveryType FROM vn2008.Tickets t JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia WHERE Id_Ticket = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp - FROM vn2008.Tickets t - LEFT JOIN vn2008.warehouse_pickup w + FROM vn2008.Tickets t + LEFT JOIN vn2008.warehouse_pickup w ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id WHERE t.Id_Ticket = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -41673,30 +41677,30 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `getNextDueDate`(vDated DATE, vGapDays INT, vPayDay INT) RETURNS date NO SQL -BEGIN - - DECLARE vReturn DATE; - DECLARE vDuaDate DATE; - DECLARE vDuaDateDay INT; - - SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate; - - IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); - ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); - END IF; - - IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN - IF util.isLeapYear(YEAR(vDuaDate)) THEN - SET vPayDay = 29; - ELSE - SET vPayDay = 28; - END IF; - END IF; - - SELECT DAY(vDuaDate) INTO vDuaDateDay; - RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay))); +BEGIN + + DECLARE vReturn DATE; + DECLARE vDuaDate DATE; + DECLARE vDuaDateDay INT; + + SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate; + + IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN + SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); + ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN + SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); + END IF; + + IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN + IF util.isLeapYear(YEAR(vDuaDate)) THEN + SET vPayDay = 29; + ELSE + SET vPayDay = 28; + END IF; + END IF; + + SELECT DAY(vDuaDate) INTO vDuaDateDay; + RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay))); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41717,11 +41721,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getShipmentHour`(vTicket INT) RETURN READS SQL DATA BEGIN DECLARE vShipmentHour INT; - + SELECT HOUR(shipped) INTO vShipmentHour FROM ticket WHERE id = vTicket; - + IF vShipmentHour = 0 THEN DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; @@ -41736,11 +41740,11 @@ BEGIN JOIN agencyMode am on am.id = t.agencyModeFk JOIN address a on a.id = t.addressFk WHERE t.id = vTicket; - - SELECT Hora INTO vShipmentHour + + SELECT Hora INTO vShipmentHour FROM tmp.production_buffer; END IF; - + RETURN vShipmentHour; END ;; DELIMITER ; @@ -41765,12 +41769,12 @@ BEGIN SELECT rate3 INTO price FROM vn.priceFixed - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; - SELECT `value` INTO price + SELECT `value` INTO price FROM vn.specialPrice - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND clientFk = vClientFk ; RETURN price; END ;; @@ -41795,23 +41799,23 @@ BEGIN /** * Devuelve el ticket que debe de preparar el trabajador * - * @param vWorker Id del trabajador + * @param vWorker Id del trabajador * @param vWarehouse Id del almacén * @return Id del ticket * * #UPDATED PAK 2019/08/16 * #PENDING REVIEW **/ - + DECLARE vToday DATETIME DEFAULT util.VN_CURDATE(); DECLARE vYesterday DATETIME; DECLARE vTodayvMidniight DATETIME DEFAULT midnight(vToday); DECLARE vTicket INT DEFAULT NULL; DECLARE PREVIOUS_PREPARATION INT; DECLARE vHasBeenPreviouslyPrepared INT DEFAULT 0; - + -- Si hay algun ticket previamente seleccionado, y se ha quedado sin empezar, lo recupera en primer lugar. - /* + /* SELECT i.Id_Ticket INTO vTicket FROM vncontrol.inter i JOIN vn.state s ON s.id = i.state_id @@ -41828,7 +41832,7 @@ BEGIN AND i.Id_Trabajador = vWorker AND sub.ticketFk IS NULL LIMIT 1; - + IF vTicket IS NULL THEN */ SELECT id INTO PREVIOUS_PREPARATION @@ -41836,20 +41840,20 @@ BEGIN WHERE code LIKE 'PREVIOUS_PREPARATION'; SET vYesterday = TIMESTAMPADD(DAY,-1,vToday); - + DROP TEMPORARY TABLE IF EXISTS tmp.workerComercial; CREATE TEMPORARY TABLE tmp.workerComercial ENGINE = MEMORY - SELECT workerFk as worker FROM `grant` g - JOIN grantGroup gg ON g.`groupFk` = gg.id + SELECT workerFk as worker FROM `grant` g + JOIN grantGroup gg ON g.`groupFk` = gg.id WHERE gg.description = 'Comerciales'; - - DELETE wc.* + + DELETE wc.* FROM tmp.workerComercial wc JOIN `grant` g ON g.workerFk = wc.worker - JOIN grantGroup gg ON g.`groupFk` = gg.id - WHERE gg.description = 'Gerencia'; - + JOIN grantGroup gg ON g.`groupFk` = gg.id + WHERE gg.description = 'Gerencia'; + DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; CREATE TEMPORARY TABLE tmp.production_buffer ENGINE = MEMORY @@ -41870,18 +41874,18 @@ BEGIN LEFT JOIN vn.zone z ON z.id = t.zoneFk WHERE t.shipped BETWEEN vYesterday AND vTodayvMidniight AND t.warehouseFk = vWarehouse - AND + AND ( (tls.code = 'PRINTED' AND wc.worker IS NULL) - OR + OR (tls.code ='PICKER_DESIGNED' AND tls.worker = vWorker) - OR + OR (tls.code = 'PRINTED_BACK') - OR + OR (tls.code = 'PRINTED PREVIOUS') ); - - + + SELECT ticket INTO vTicket FROM tmp.production_buffer ORDER BY (code = 'PICKER_DESIGNED') DESC, (code = 'PRINTED PREVIOUS') DESC ,Hora, Minuto, loadingOrder @@ -41892,15 +41896,15 @@ BEGIN FROM vncontrol.inter WHERE Id_Ticket = vTicket AND state_id = PREVIOUS_PREPARATION; - - IF vHasBeenPreviouslyPrepared AND ticketWarehouseGet(vTicket) = 1 THEN - + + IF vHasBeenPreviouslyPrepared AND ticketWarehouseGet(vTicket) = 1 THEN + INSERT IGNORE INTO vn.ticketDown(ticketFk) VALUES(vTicket); - + END IF; -- END IF; - + RETURN vTicket; END ;; @@ -41924,7 +41928,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket BEGIN DECLARE vLabelCount INT DEFAULT 0; - SELECT labelCount INTO vLabelCount + SELECT labelCount INTO vLabelCount FROM ticketTrolley WHERE ticket = vTicket; @@ -42028,7 +42032,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1) DETERMINISTIC -BEGIN +BEGIN /* Calcula si existe alguna base imponible negativa * Requiere la tabla temporal vn.ticketToInvoice(id) @@ -42036,14 +42040,14 @@ BEGIN * returns BOOLEAN */ DECLARE hasAnyNegativeBase BOOLEAN; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; CREATE TEMPORARY TABLE tmp.ticket (KEY (ticketFk)) ENGINE = MEMORY SELECT id ticketFk FROM ticketToInvoice; - + CALL ticket_getTax(NULL); SELECT COUNT(*) INTO hasAnyNegativeBase @@ -42056,9 +42060,9 @@ BEGIN DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticket; - + RETURN hasAnyNegativeBase; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42080,17 +42084,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSe BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42113,7 +42117,7 @@ BEGIN DECLARE vCountry INT; DECLARE hasSomeNegativeBase BOOLEAN; - SELECT s.countryFk + SELECT s.countryFk INTO vCountry FROM supplier s JOIN ticket t ON t.companyFk = s.id @@ -42122,9 +42126,9 @@ BEGIN SELECT COUNT(*) INTO hasSomeNegativeBase FROM ( SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = vCountry WHERE s.ticketFk = vTicket GROUP BY itc.taxClassFk @@ -42154,12 +42158,12 @@ BEGIN DECLARE totalAmount DECIMAL(10,2); SELECT SUM(vat) INTO totalAmount - FROM ( + FROM ( SELECT iot.vat FROM invoiceOutTax iot JOIN invoiceOut io ON io.id = iot.invoiceOutFk WHERE io.ref = vInvoiceRef - UNION ALL + UNION ALL SELECT ioe.amount FROM invoiceOutExpence ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk @@ -42189,7 +42193,7 @@ BEGIN DECLARE vIssued DATE; DECLARE vSerial VARCHAR(15); - SELECT issued, ref + SELECT issued, ref INTO vIssued, vSerial FROM invoiceOut WHERE id = vSelf; @@ -42260,9 +42264,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompa DETERMINISTIC BEGIN /** - * Obtiene la serie de de una factura + * Obtiene la serie de de una factura * dependiendo del area del cliente. - * + * * @param vClientFk Id del cliente * @param vCompanyFk Id de la empresa * @param vType Tipo de factura ["R", "M", "G"] @@ -42361,7 +42365,7 @@ BEGIN JOIN vn.entry e ON e.companyFk = co.id WHERE e.id = vEntryFk AND c.isUeeMember = TRUE; - + IF vSupplierCountry != vClientCountry AND vSupplierCountry * vClientCountry > 0 THEN SET isIntrastatOperation = TRUE; END IF; @@ -42385,19 +42389,19 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1) DETERMINISTIC -BEGIN - - DECLARE vIsLogifloraDay BOOLEAN; - - SELECT COUNT(*) INTO vIsLogifloraDay - FROM edi.warehouseFloramondo wf - JOIN vn.floramondoConfig fc - WHERE wf.warehouseFk = vWarehouse - AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) - AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); - - RETURN vIsLogifloraDay; - +BEGIN + + DECLARE vIsLogifloraDay BOOLEAN; + + SELECT COUNT(*) INTO vIsLogifloraDay + FROM edi.warehouseFloramondo wf + JOIN vn.floramondoConfig fc + WHERE wf.warehouseFk = vWarehouse + AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) + AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); + + RETURN vIsLogifloraDay; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42434,7 +42438,7 @@ BEGIN WHERE sl.scan_id = vScanId AND t.Id_Ruta ) t1; - + RETURN vDistinctRoutesInThePallet = 1; END ;; DELIMITER ; @@ -42458,20 +42462,20 @@ BEGIN DECLARE vPacking INTEGER DEFAULT 0; DECLARE vItemFk INTEGER; - + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - - SELECT IFNULL(packing,0) INTO vPacking - FROM vn.buy + + SELECT IFNULL(packing,0) INTO vPacking + FROM vn.buy WHERE id = CAST(vBarcode AS DECIMAL(18,0)); - - - - + + + + IF NOT vPacking THEN CALL cache.last_buy_refresh(FALSE); SELECT IFNULL(packing,1) INTO vPacking - FROM + FROM (SELECT packing , created FROM vn.itemShelving WHERE itemFk = vItemFk @@ -42484,11 +42488,11 @@ BEGIN ) packings ORDER BY created desc LIMIT 1; - + END IF; - + RETURN vPacking; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42513,11 +42517,11 @@ BEGIN DECLARE vColumn INT; DECLARE vClosestParkingFk INT; DECLARE vSectorFk INT; - + SELECT p.column, sectorFk INTO vColumn, vSectorFk FROM vn.parking p WHERE p.id = vParkingFk; - + SELECT itemShelvingFk INTO vClosestParkingFk FROM ( @@ -42527,12 +42531,12 @@ BEGIN JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk WHERE p.sectorFk = vSectorFk AND ipsl.saldo > 0 - ) sub + ) sub ORDER BY distance LIMIT 1; - + RETURN vClosestParkingFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42554,17 +42558,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vS BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42607,17 +42611,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getFhImage`(itemFk INT) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - DECLARE vImageUrl VARCHAR(255); - SELECT sr.PictureReference INTO vImageUrl - FROM vn.buy b - JOIN edi.ekt e ON b.ektFk = e.id - JOIN edi.supplyResponse sr ON sr.Item_ArticleCode =e.`ref` - JOIN vn.item i ON i.id = b.itemFk - WHERE b.itemFk = itemFk - ORDER BY (sr.EmbalageCode = e.package) DESC - LIMIT 1; - RETURN vImageUrl; +BEGIN + DECLARE vImageUrl VARCHAR(255); + SELECT sr.PictureReference INTO vImageUrl + FROM vn.buy b + JOIN edi.ekt e ON b.ektFk = e.id + JOIN edi.supplyResponse sr ON sr.Item_ArticleCode =e.`ref` + JOIN vn.item i ON i.id = b.itemFk + WHERE b.itemFk = itemFk + ORDER BY (sr.EmbalageCode = e.package) DESC + LIMIT 1; + RETURN vImageUrl; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42636,30 +42640,30 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - - DECLARE vDiameter INT; - DECLARE vPackageFk VARCHAR(50); - DECLARE vCoeficient DOUBLE DEFAULT 1.08; - - SELECT MAX(LEFT(value,3)) INTO vDiameter - FROM vn.itemTag it - JOIN vn.tag t ON t.id = it.tagFk - WHERE it.itemFk = vItemFk - AND t.overwrite = 'diameter'; - - SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) - INTO vPackageFk - FROM vn.volumeConfig vc; - - INSERT IGNORE INTO vn.packaging(id, width, `depth`) - SELECT vPackageFk, - FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), - FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) - FROM vn.volumeConfig vc; - - RETURN vPackageFk; - +BEGIN + + DECLARE vDiameter INT; + DECLARE vPackageFk VARCHAR(50); + DECLARE vCoeficient DOUBLE DEFAULT 1.08; + + SELECT MAX(LEFT(value,3)) INTO vDiameter + FROM vn.itemTag it + JOIN vn.tag t ON t.id = it.tagFk + WHERE it.itemFk = vItemFk + AND t.overwrite = 'diameter'; + + SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) + INTO vPackageFk + FROM vn.volumeConfig vc; + + INSERT IGNORE INTO vn.packaging(id, width, `depth`) + SELECT vPackageFk, + FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), + FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) + FROM vn.volumeConfig vc; + + RETURN vPackageFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42696,7 +42700,7 @@ BEGIN FROM packaging p JOIN item i ON i.id = vSelf WHERE p.id = vPackaging; - + RETURN vVolume; END ;; @@ -42717,7 +42721,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date DETERMINISTIC -BEGIN +BEGIN /** * Returns the date of the last day of the week * @@ -42753,23 +42757,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(10)) RETURNS tinyint(1) READS SQL DATA -BEGIN -/** - * Comprueba si existe matrícula - * - * @param vPlate matrícula del vehículo - * @return Devuelve TRUE en caso de que exista - * - */ - - IF (SELECT COUNT(*) - FROM machine m - WHERE m.plate = vPlate - ) THEN - RETURN TRUE; - ELSE - RETURN FALSE; - END IF; +BEGIN +/** + * Comprueba si existe matrícula + * + * @param vPlate matrícula del vehículo + * @return Devuelve TRUE en caso de que exista + * + */ + + IF (SELECT COUNT(*) + FROM machine m + WHERE m.plate = vPlate + ) THEN + RETURN TRUE; + ELSE + RETURN FALSE; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42792,9 +42796,9 @@ BEGIN DECLARE result INT; DECLARE vSenderFk INT; - SELECT id INTO vSenderFk + SELECT id INTO vSenderFk FROM account.user WHERE `name` = account.myUser_getName(); - + RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage)); END ;; DELIMITER ; @@ -42821,9 +42825,9 @@ BEGIN DECLARE vSendDate DATETIME DEFAULT util.VN_NOW(); DECLARE vSender VARCHAR(255) CHARSET utf8; - SELECT `name` INTO vSender + SELECT `name` INTO vSender FROM account.user WHERE id = vSenderFK; - + SET vRecipient = LOWER(vRecipient); DROP TEMPORARY TABLE IF EXISTS tRecipients; @@ -42844,7 +42848,7 @@ BEGIN IF vCount = 0 THEN RETURN vCount; - END IF; + END IF; SET vUuid = UUID(); @@ -42855,7 +42859,7 @@ BEGIN message = vMessage, sendDate = vSendDate; - INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) + INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate FROM tRecipients; @@ -42929,7 +42933,7 @@ BEGIN -- Devuelte el volumen total de la orden sumada DECLARE vWarehouseId INTEGER; DECLARE vVolume DECIMAL(10,3); - + SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume FROM hedera.orderRow o JOIN item i ON i.id = o.itemFk @@ -43006,7 +43010,7 @@ BEGIN WHERE cb.id = packagingReturnFk; SET vValue = IF (vAmount IS NULL, - IFNULL(base,0), + IFNULL(base,0), vAmount / IFNULL(upload, 0) + IFNULL(base, 0)); ELSE SET vValue = IFNULL(price, 0) + IFNULL(base, 0); @@ -43033,7 +43037,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RET DETERMINISTIC BEGIN DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; -SELECT +SELECT GROUP_CONCAT(i.id, ':', ppa.denomination, @@ -43090,20 +43094,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -43111,16 +43115,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -43132,7 +43136,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -43157,9 +43161,9 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; DECLARE vShipped DATETIME; - + SELECT addressFk, date(shipped) INTO vAddressFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; SELECT routeFk INTO vRouteFk @@ -43173,7 +43177,7 @@ BEGIN ORDER BY friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -43197,20 +43201,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -43218,16 +43222,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -43239,7 +43243,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -43259,27 +43263,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1) READS SQL DATA -BEGIN - - DECLARE vIsForbbiden BOOL; - DECLARE vLeft INT; - - SELECT zg.lft INTO vLeft - FROM vn.address a - JOIN vn.zoneGeo zg ON zg.name = a.postalCode - WHERE a.id = vAddressFk; - - SELECT sgi.isForbidden INTO vIsForbbiden - FROM vn.specieGeoInvasive sgi - JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk - JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) - WHERE vLeft BETWEEN zg.lft AND zg.rgt - AND ib.itemFk = vItemFk - ORDER BY zg.`depth` DESC - LIMIT 1; - - RETURN IFNULL(vIsForbbiden, FALSE); - +BEGIN + + DECLARE vIsForbbiden BOOL; + DECLARE vLeft INT; + + SELECT zg.lft INTO vLeft + FROM vn.address a + JOIN vn.zoneGeo zg ON zg.name = a.postalCode + WHERE a.id = vAddressFk; + + SELECT sgi.isForbidden INTO vIsForbbiden + FROM vn.specieGeoInvasive sgi + JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk + JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) + WHERE vLeft BETWEEN zg.lft AND zg.rgt + AND ib.itemFk = vItemFk + ORDER BY zg.`depth` DESC + LIMIT 1; + + RETURN IFNULL(vIsForbbiden, FALSE); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43299,7 +43303,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC BEGIN - + DECLARE vLetraInicial VARCHAR(1); DECLARE vLetraFinal VARCHAR(1); DECLARE vParteNumerica VARCHAR(7); @@ -43311,60 +43315,60 @@ BEGIN SET vLetraInicial = SUBSTR(vCIF, 1, 1); SET vLetraFinal = SUBSTR(vCIF, 9, 1); SET vParteNumerica = SUBSTR(vCIF, 2, 7); - - WHILE i < 7 DO - + + WHILE i < 7 DO + SET i = i + 1; - + SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0)); - + IF i MOD 2 THEN - + SET vNumero = vNumero * 2; SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10); - + END IF; - + SET vSuma = vSuma + vNumero; - + END WHILE; - + SET vSuma = vSuma MOD 10; - + IF vSuma > 0 THEN - + SET vSuma = 10 - vSuma; - + END IF; - + -- Comprobación de dígito de control IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN - + SET vResult = TRUE; - + END IF; - + IF vSuma = 0 THEN - + SET vSuma = 10; - + END IF; - + IF CHAR(64 + vSuma) = vLetraFinal THEN - + SET vResult = TRUE; - + END IF; - + -- Sólo se aceptan letras como caracter inicial IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W - + SET vResult = FALSE; - + END IF; - + RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43383,55 +43387,55 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC -BEGIN - - DECLARE vIndice INT; - DECLARE vNumero VARCHAR(7); - DECLARE vOperador VARCHAR(9); - DECLARE vParteNumerica DECIMAL(8,0); - DECLARE vLetraInicial VARCHAR(1); - DECLARE vLetraFinal VARCHAR(1); - DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; - - SET vLetraInicial = SUBSTR(vNIE, 1, 1); - SET vLetraFinal = SUBSTR(vNIE, 9, 1); - SET vNumero = SUBSTR(vNIE, 2, 7); - - CASE vLetraInicial - - WHEN 'X' THEN - - SET vOperador = "0"; - - WHEN 'Y' THEN - - SET vOperador = "1"; - - WHEN 'Z' THEN - - SET vOperador = "2"; - - ELSE - - SET vLetraInicialEsIncorrecta = TRUE; - - END CASE; - - SET vOperador = CONCAT(vOperador, vNumero); - SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); - SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; - - IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN - - RETURN TRUE; - - ELSE - - RETURN FALSE; - - END IF; - +BEGIN + + DECLARE vIndice INT; + DECLARE vNumero VARCHAR(7); + DECLARE vOperador VARCHAR(9); + DECLARE vParteNumerica DECIMAL(8,0); + DECLARE vLetraInicial VARCHAR(1); + DECLARE vLetraFinal VARCHAR(1); + DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; + DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; + + SET vLetraInicial = SUBSTR(vNIE, 1, 1); + SET vLetraFinal = SUBSTR(vNIE, 9, 1); + SET vNumero = SUBSTR(vNIE, 2, 7); + + CASE vLetraInicial + + WHEN 'X' THEN + + SET vOperador = "0"; + + WHEN 'Y' THEN + + SET vOperador = "1"; + + WHEN 'Z' THEN + + SET vOperador = "2"; + + ELSE + + SET vLetraInicialEsIncorrecta = TRUE; + + END CASE; + + SET vOperador = CONCAT(vOperador, vNumero); + SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); + SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; + + IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN + + RETURN TRUE; + + ELSE + + RETURN FALSE; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43450,29 +43454,29 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIF`(vNIF VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC -BEGIN - - DECLARE vIndice INT; - DECLARE vParteNumerica DECIMAL(8,0); - DECLARE vLetra VARCHAR(1); - DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - - SET vLetra = SUBSTRING(vNIF, 9, 1); - - SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); - - SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; - - If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then - - RETURN TRUE; - - ELSE - - RETURN FALSE; - - END IF; - +BEGIN + + DECLARE vIndice INT; + DECLARE vParteNumerica DECIMAL(8,0); + DECLARE vLetra VARCHAR(1); + DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; + + SET vLetra = SUBSTRING(vNIF, 9, 1); + + SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); + + SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; + + If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then + + RETURN TRUE; + + ELSE + + RETURN FALSE; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43492,21 +43496,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC BEGIN - + /* * return message with tickets and collection if there is tickets of a collection without expeditions - * + * * @param vCollectionFk the collection to check * @return an array with collection and tickets without expeditions - * + * */ - + DECLARE vAnswer VARCHAR(100) DEFAULT ''; IF collection_isPacked(vCollectionFk) = FALSE THEN SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer FROM vn.ticketCollection tc - LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk + LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND ISNULL(e.id); END IF; @@ -43552,9 +43556,9 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, tmp.ticketTotal; - + RETURN vTotal; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43573,79 +43577,79 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8 DETERMINISTIC -BEGIN - - DECLARE vRestTicketsMaxOrder INT; - DECLARE vRestTicketsMinOrder INT; - DECLARE vRestTicketsPacking INT; - DECLARE vMyProductionOrder INT; - DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; - DECLARE vMyPath INT; - DECLARE vMyWarehouse INT; - DECLARE PACKING_ORDER INT; - DECLARE vExpeditionsCount INT; - DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; - -SELECT `order` - INTO PACKING_ORDER - FROM state - WHERE code = 'PACKING'; - -SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) - INTO vMyPath, vMyWarehouse, vMyProductionOrder - FROM ticket t - LEFT JOIN ticketState ts on ts.ticket = t.id - WHERE t.id = vTicketId; - -SELECT (ag.`name` = 'VN_VALENCIA') - INTO vIsValenciaPath - FROM vn2008.Rutas r - JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia - JOIN vn2008.agency ag on ag.agency_id = a.agency_id - WHERE r.Id_Ruta = vMyPath; - -IF vIsValenciaPath THEN -- Rutas Valencia - - SELECT COUNT(*) - INTO vExpeditionsCount - FROM expedition e - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk = vMyPath; - - SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) - INTO vRestTicketsMaxOrder, vRestTicketsMinOrder - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE t.routeFk = vMyPath - AND t.warehouseFk = vMyWarehouse - AND t.id != vTicketid; - - SELECT COUNT(*) - INTO vRestTicketsPacking - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE ts.productionOrder = PACKING_ORDER - AND t.routeFk = vMyPath - AND t.warehouseFk = vMyWarehouse - AND t.id != vTicketid; - - IF vExpeditionsCount = 1 THEN - SET vPosition = 'FIRST'; - ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN - SET vPosition = 'LAST'; - ELSEIF vRestTicketsPacking THEN - SET vPosition = 'SHARED'; - ELSE - SET vPosition = 'MID'; - END IF; - -ELSE - SET vPosition = 'MID'; - -END IF; - -RETURN vPosition; - +BEGIN + + DECLARE vRestTicketsMaxOrder INT; + DECLARE vRestTicketsMinOrder INT; + DECLARE vRestTicketsPacking INT; + DECLARE vMyProductionOrder INT; + DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; + DECLARE vMyPath INT; + DECLARE vMyWarehouse INT; + DECLARE PACKING_ORDER INT; + DECLARE vExpeditionsCount INT; + DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; + +SELECT `order` + INTO PACKING_ORDER + FROM state + WHERE code = 'PACKING'; + +SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) + INTO vMyPath, vMyWarehouse, vMyProductionOrder + FROM ticket t + LEFT JOIN ticketState ts on ts.ticket = t.id + WHERE t.id = vTicketId; + +SELECT (ag.`name` = 'VN_VALENCIA') + INTO vIsValenciaPath + FROM vn2008.Rutas r + JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia + JOIN vn2008.agency ag on ag.agency_id = a.agency_id + WHERE r.Id_Ruta = vMyPath; + +IF vIsValenciaPath THEN -- Rutas Valencia + + SELECT COUNT(*) + INTO vExpeditionsCount + FROM expedition e + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk = vMyPath; + + SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) + INTO vRestTicketsMaxOrder, vRestTicketsMinOrder + FROM ticket t + LEFT JOIN ticketState ts on t.id = ts.ticket + WHERE t.routeFk = vMyPath + AND t.warehouseFk = vMyWarehouse + AND t.id != vTicketid; + + SELECT COUNT(*) + INTO vRestTicketsPacking + FROM ticket t + LEFT JOIN ticketState ts on t.id = ts.ticket + WHERE ts.productionOrder = PACKING_ORDER + AND t.routeFk = vMyPath + AND t.warehouseFk = vMyWarehouse + AND t.id != vTicketid; + + IF vExpeditionsCount = 1 THEN + SET vPosition = 'FIRST'; + ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN + SET vPosition = 'LAST'; + ELSEIF vRestTicketsPacking THEN + SET vPosition = 'SHARED'; + ELSE + SET vPosition = 'MID'; + END IF; + +ELSE + SET vPosition = 'MID'; + +END IF; + +RETURN vPosition; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43675,9 +43679,9 @@ BEGIN LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id WHERE ticketFk = vTicketFk ) sub; - + RETURN IFNULL(vSplitCounter,'--'); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43726,21 +43730,21 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolumeBoxes`(vTicketId IN DETERMINISTIC BEGIN -/* +/* * Devuelve el volumen estimado del ticket sumado, en cajas * * vTicketId Numero de ticket - * + * */ DECLARE vVolumeBoxM3 DOUBLE; DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1); DECLARE vVnBoxId VARCHAR(10) DEFAULT '94'; - + SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId; - + SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3; - + RETURN vTicketTotalVolumeBoxes; END ;; @@ -43765,7 +43769,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM ticket + FROM ticket WHERE id = vTicketFk; RETURN vWarehouseFk; @@ -43787,21 +43791,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1) READS SQL DATA -BEGIN - - DECLARE vCC DECIMAL(10,1); - - SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) - INTO vCC - FROM vn.saleVolume sv - JOIN vn.sale s ON s.id = sv.saleFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.packaging p ON p.id = 'CC' - JOIN vn.volumeConfig vc - WHERE sv.ticketFk = vTicketFk; - - RETURN vCC; - +BEGIN + + DECLARE vCC DECIMAL(10,1); + + SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) + INTO vCC + FROM vn.saleVolume sv + JOIN vn.sale s ON s.id = sv.saleFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.packaging p ON p.id = 'CC' + JOIN vn.volumeConfig vc + WHERE sv.ticketFk = vTicketFk; + + RETURN vCC; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43821,44 +43825,44 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11) READS SQL DATA proc:BEGIN - + /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * + * * @param vParamFk Número a validar * @return vValidFk Identificador validado */ - + DECLARE vValidFk INT; -- Tabla vn.saleGroup SELECT s.ticketFk INTO vValidFk FROM vn.sale s JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk + JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk WHERE sg.id = vParamFk AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) LIMIT 1; - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.collection SELECT c.id INTO vValidFk - FROM vn.collection c + FROM vn.collection c WHERE c.id = vParamFk AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.ticket @@ -43866,17 +43870,17 @@ proc:BEGIN FROM vn.ticket t WHERE t.id = vParamFk AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; RETURN NULL; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43902,8 +43906,8 @@ BEGIN * @vTicketFk Id del ticket a calcular */ DECLARE deliveryPrice DECIMAL (10,2); - - IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id + + IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id WHERE t.id = vTicketFk) THEN SELECT SUM(sv.freight) INTO deliveryPrice FROM vn.saleVolume sv @@ -43914,7 +43918,7 @@ BEGIN LEFT JOIN expedition e ON e.ticketFk = t.id JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk WHERE t.id = vTicketFk; - + END IF; RETURN deliveryPrice; END ;; @@ -43935,21 +43939,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RETURNS decimal(10,3) READS SQL DATA -BEGIN -/** - * Devuelve el peso total del ticket - * - * @return Total peso - */ - - DECLARE vWeight DECIMAL(10,3); - - SELECT sum(weight) INTO vWeight - FROM saleVolume - WHERE ticketFk = vTicketFk; - - RETURN vWeight; - +BEGIN +/** + * Devuelve el peso total del ticket + * + * @return Total peso + */ + + DECLARE vWeight DECIMAL(10,3); + + SELECT sum(weight) INTO vWeight + FROM saleVolume + WHERE ticketFk = vTicketFk; + + RETURN vWeight; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43978,10 +43982,10 @@ BEGIN * @param vAddressFk Consignatario * @param vCompanyFk Empresa * @param vAgencyModeFk agencia - */ - + */ + DECLARE vTicket INT; - + SELECT t.id INTO vTicket FROM vn.ticket t WHERE (t.clientFk <=> vClientFk OR vClientFk IS NULL) @@ -43991,7 +43995,7 @@ BEGIN AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL) AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL) LIMIT 1; - + IF vTicket IS NULL THEN CALL vn.ticket_add( vClientFk, @@ -44007,7 +44011,7 @@ BEGIN vTicket ); END IF; - + RETURN vTicket; END ;; DELIMITER ; @@ -44027,18 +44031,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1) READS SQL DATA -BEGIN - - DECLARE hasUbication BOOL; - - SELECT COUNT(*) INTO hasUbication - FROM vn.ticket t - JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - WHERE rm.beachFk - AND t.id = vTicketFk; - - RETURN hasUbication; - +BEGIN + + DECLARE hasUbication BOOL; + + SELECT COUNT(*) INTO hasUbication + FROM vn.ticket t + JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + WHERE rm.beachFk + AND t.id = vTicketFk; + + RETURN hasUbication; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44151,7 +44155,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUse READS SQL DATA BEGIN /** - * Verifica la dirección de la fichada + * Verifica la dirección de la fichada * @param vUserFk Identificador del trabajador * @param vTimed Hora de la fichada * @return Retorna sentido de la fichada 'in, out, middle' @@ -44164,40 +44168,40 @@ BEGIN DECLARE vDayStayMax INT; DECLARE vTimedSeconds INT; DECLARE vLastTimeIn INT; - + SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; - + SELECT dayStayMax INTO vDayStayMax FROM vn.workerTimeControlParams; SELECT timed, direction INTO vNext,vNextDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed > vTimed ORDER BY timed ASC LIMIT 1; - + SELECT timed, direction INTO vPrevious, vPreviousDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - - IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN + LIMIT 1; + + IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN RETURN 'middle'; END IF; - - + + IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN - IF vPreviousDirection = 'in' THEN + IF vPreviousDirection = 'in' THEN RETURN 'out'; ELSE SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction ='in' AND timed < vPrevious; IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN @@ -44251,11 +44255,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén. * Si no existe lo genera. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -44263,8 +44267,8 @@ BEGIN DECLARE vTravelFk INT; IF vLanded THEN - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -44275,14 +44279,14 @@ BEGIN AND landed = vLanded; IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) - SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id - FROM vn.warehouse wOut + SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id + FROM vn.warehouse wOut JOIN vn.agencyMode am ON am.name = 'LOGIFLORA' WHERE wOut.name = 'Holanda'; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -44290,11 +44294,11 @@ BEGIN AND wOut.name = 'Holanda' AND landed = vLanded; END IF; - + END IF; - + RETURN vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44321,21 +44325,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44362,21 +44366,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44454,24 +44458,24 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `workerMachinery_isRegistered`(vWorkerFk VARCHAR(10)) RETURNS tinyint(1) READS SQL DATA -BEGIN -/** - * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo) - * - * @param vWorkerFk id del trabajador - * @return Devuelve TRUE/FALSE en caso de que haya o no registros - */ - - IF (SELECT COUNT(*) - FROM machineWorker m - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed)) - THEN - RETURN TRUE; - ELSE - RETURN FALSE; - END IF; - +BEGIN +/** + * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo) + * + * @param vWorkerFk id del trabajador + * @return Devuelve TRUE/FALSE en caso de que haya o no registros + */ + + IF (SELECT COUNT(*) + FROM machineWorker m + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), util.VN_NOW()) AND ISNULL(m.outTimed)) + THEN + RETURN TRUE; + ELSE + RETURN FALSE; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44498,15 +44502,15 @@ BEGIN * @param vTimeOut * @return vNigthlyHours */ - DECLARE vNigthlyHours DECIMAL(5,2); + DECLARE vNigthlyHours DECIMAL(5,2); DECLARE vSecondsPerHour INT(4) DEFAULT 3600; - + SELECT GREATEST(0, TIMESTAMPDIFF(SECOND, - IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeIn), ' ', startNightlyHours), + IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeIn), ' ', startNightlyHours), vTimeIn), - IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeOut), ' ', endNightlyHours), + IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeOut), ' ', endNightlyHours), vTimeOut))) / vSecondsPerHour INTO vNigthlyHours FROM vn.workerTimeControlConfig; @@ -44538,47 +44542,47 @@ BEGIN 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 + 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 + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + 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); + 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 ; @@ -44607,47 +44611,47 @@ BEGIN 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 + 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 + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + 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); + 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 ; @@ -44673,17 +44677,17 @@ BEGIN * @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE */ DECLARE vLastIn DATETIME ; - + SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM vn.workerTimeControl WHERE userFk = vWorkerFk AND direction = 'in'; - IF (SELECT MOD(COUNT(*),2) - FROM vn.workerTimeControl - WHERE userFk = vWorkerFk AND + IF (SELECT MOD(COUNT(*),2) + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk AND timed >= vLastIn - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -44778,7 +44782,7 @@ BEGIN SET `type` = vType, `name` = vName, parentFk = vParentFk; - + SET vSelf = LAST_INSERT_ID(); UPDATE zoneGeoRecalc SET isChanged = TRUE; @@ -44802,7 +44806,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT) BEGIN - + DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/ INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) @@ -44830,24 +44834,24 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `addressTaxArea`() READS SQL DATA BEGIN /** - * Devuelve el taxArea para un conjunto de Consignatarios y empresas, + * Devuelve el taxArea para un conjunto de Consignatarios y empresas, * * @table tmp.addressCompany(addressFk, companyFk) valores a calcular * @return tmp.addressTaxArea(addressFk,companyFk) */ DECLARE vSpainCountryCode INT DEFAULT 1; - + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; CREATE TEMPORARY TABLE tmp.addressTaxArea (PRIMARY KEY (addressFk, companyFk)) ENGINE = MEMORY - SELECT CASE - WHEN (NOT cClient.isUeeMember OR NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN + SELECT CASE + WHEN (NOT cClient.isUeeMember OR NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN 'WORLD' - WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN + WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN 'CEE' - WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode THEN + WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode THEN 'EQU' ELSE 'NATIONAL' @@ -44884,27 +44888,27 @@ BEGIN * @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 vAgency INT; DECLARE vShipped DATE; DECLARE vLanded DATE DEFAULT util.VN_CURDATE(); SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode; l: LOOP - + CALL agencyHourGetShipped(vLanded,vAddress,vAgency); - SELECT shipped INTO vShipped + SELECT shipped INTO vShipped FROM tmp.agencyHourGetShipped WHERE warehouseFk = vWarehouse LIMIT 1; - + IF vShipped THEN LEAVE l; END IF; - + SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY); - + END LOOP; - + SELECT vShipped,vLanded; END ;; DELIMITER ; @@ -44955,7 +44959,7 @@ BEGIN LIMIT 1 ) t WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44978,14 +44982,14 @@ BEGIN * DEPRECATED usar zoneGetWarehouse * Devuelve el listado de agencias disponibles para la fecha, * dirección y warehouuse pasadas - * + * * @param vAddress no puede ser NULL * @param vWarehouse warehouse donde comprobaremos las agencias y fecha * @param vDate Fecha de recogida * @table agencyModeWarehouseList Listado de agencias disponibles */ DECLARE vAgency INT; - DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vDone BOOL DEFAULT FALSE; DECLARE vCur CURSOR FOR SELECT DISTINCT a.id FROM agency a @@ -45009,13 +45013,13 @@ BEGIN PRIMARY KEY(id) ) ENGINE = MEMORY; - + OPEN vCur; FETCH vCur INTO vAgency; WHILE NOT vDone DO - + INSERT INTO tmp.agencyModeWarehouseList SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name FROM agencyHour ah @@ -45044,7 +45048,7 @@ BEGIN END WHILE; CLOSE vCur; - + SELECT * FROM tmp.agencyModeWarehouseList; DROP TEMPORARY TABLE tmp.agencyModeWarehouseList; END ;; @@ -45070,9 +45074,9 @@ BEGIN CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency); SELECT * FROM tmp.agencyHourGetShipped; - + DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45110,7 +45114,7 @@ BEGIN DECLARE cWarehouses CURSOR FOR SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -45119,7 +45123,7 @@ BEGIN CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( + CREATE TEMPORARY TABLE tmp.availableCalc( calcFk INT UNSIGNED, PRIMARY KEY (calcFk) ) @@ -45130,7 +45134,7 @@ BEGIN l: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouse, vShipment; - + IF vDone THEN LEAVE l; END IF; @@ -45163,7 +45167,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2 BEGIN /** * If the bic length is Incorrect throw exception - * + * * @param vBic bic code */ @@ -45171,7 +45175,7 @@ BEGIN SELECT bicLength INTO vConfigBicLenght FROM vn.bankEntityConfig bec; - + IF LENGTH(vBic) <> vConfigBicLenght THEN CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght )); END IF; @@ -45198,14 +45202,14 @@ BEGIN * Manda correo cuando caduca un seguro * de los leasing * -*/ +*/ INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'administracion@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body - FROM vn.bankPolicy bp - LEFT JOIN vn.supplier s + FROM vn.bankPolicy bp + LEFT JOIN vn.supplier s ON s.id = bp.supplierFk LEFT JOIN vn.bank b ON b.id = bp.bankFk @@ -45227,39 +45231,39 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) -BEGIN -/** - * Calcula las últimas compras realizadas hasta una fecha - * - * @param vWarehouseFk Id del almacén - * @param vDated Compras hasta fecha - * @return tmp.buyUltimate - */ - CALL cache.last_buy_refresh (FALSE); - - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; - CREATE TEMPORARY TABLE tmp.buyUltimate - (PRIMARY KEY (itemFk, warehouseFk), - INDEX(itemFk)) - ENGINE = MEMORY - SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing - FROM cache.last_buy - WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; - - CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); - - REPLACE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed <= vDated; - - INSERT IGNORE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed > vDated; - +BEGIN +/** + * Calcula las últimas compras realizadas hasta una fecha + * + * @param vWarehouseFk Id del almacén + * @param vDated Compras hasta fecha + * @return tmp.buyUltimate + */ + CALL cache.last_buy_refresh (FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; + CREATE TEMPORARY TABLE tmp.buyUltimate + (PRIMARY KEY (itemFk, warehouseFk), + INDEX(itemFk)) + ENGINE = MEMORY + SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing + FROM cache.last_buy + WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; + + CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); + + REPLACE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed <= vDated; + + INSERT IGNORE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed > vDated; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45420,81 +45424,81 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`(vSelf INT) -BEGIN -/** - * Triggered actions when a buy is updated or inserted. - * - * @param vSelf The buy reference - */ - DECLARE vEntryFk INT; - DECLARE vItemFk INT; - DECLARE vPackingOut DECIMAL(10,2); - DECLARE vWarehouse INT; - DECLARE vStandardFlowerBox INT; - DECLARE vWarehouseOut INT; - DECLARE vIsMerchandise BOOL; - DECLARE vIsFeedStock BOOL; - DECLARE vWeight DECIMAL(10,2); - DECLARE vPacking INT; - - SELECT b.entryFk, - b.itemFk, - i.packingOut, - ic.merchandise, - vc.standardFlowerBox, - b.weight, - b.packing - INTO - vEntryFk, - vItemFk, - vPackingOut, - vIsMerchandise, - vStandardFlowerBox, - vWeight, - vPacking - FROM buy b - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox - JOIN volumeConfig vc ON TRUE - WHERE b.id = vSelf; - - SELECT t.warehouseInFk, t.warehouseOutFk - INTO vWarehouse, vWarehouseOut - FROM entry e - JOIN travel t ON t.id = e.travelFk - WHERE e.id = vEntryFk; - - IF vIsMerchandise THEN - - REPLACE itemCost SET - itemFk = vItemFk, - warehouseFk = vWarehouse, - cm3 = buy_getUnitVolume(vSelf), - cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); - - IF vWeight AND vPacking THEN - UPDATE itemCost SET - grams = vWeight * 1000 / vPacking - WHERE itemFk = vItemFk - AND warehouseFk = vWarehouse; - END IF; - END IF; - - SELECT isFeedStock INTO vIsFeedStock - FROM warehouse WHERE id = vWarehouseOut; - - IF vIsFeedStock THEN - INSERT IGNORE INTO producer(`name`) - SELECT es.company_name - FROM buy b - JOIN edi.ekt be ON be.id = b.ektFk - JOIN edi.supplier es ON es.supplier_id = be.pro - WHERE b.id = vSelf; - - END IF; - +BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vPackingOut DECIMAL(10,2); + DECLARE vWarehouse INT; + DECLARE vStandardFlowerBox INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + DECLARE vWeight DECIMAL(10,2); + DECLARE vPacking INT; + + SELECT b.entryFk, + b.itemFk, + i.packingOut, + ic.merchandise, + vc.standardFlowerBox, + b.weight, + b.packing + INTO + vEntryFk, + vItemFk, + vPackingOut, + vIsMerchandise, + vStandardFlowerBox, + vWeight, + vPacking + FROM buy b + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox + JOIN volumeConfig vc ON TRUE + WHERE b.id = vSelf; + + SELECT t.warehouseInFk, t.warehouseOutFk + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + IF vIsMerchandise THEN + + REPLACE itemCost SET + itemFk = vItemFk, + warehouseFk = vWarehouse, + cm3 = buy_getUnitVolume(vSelf), + cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); + + IF vWeight AND vPacking THEN + UPDATE itemCost SET + grams = vWeight * 1000 / vPacking + WHERE itemFk = vItemFk + AND warehouseFk = vWarehouse; + END IF; + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut; + + IF vIsFeedStock THEN + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45542,7 +45546,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DAT BEGIN /** * Devuelve las ventas de una compra - * + * * @param vSelf Identificador de vn.buy */ DECLARE vItemFk INT; @@ -45638,11 +45642,11 @@ BEGIN -- Devuelve los splits creados SELECT CONCAT(sp.counter,'/',sp.labels) labels, COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination, - s.itemFk, - i.longName, - i.`size`, - vn.ticketSplitCounter(t.id) counter, - IF(sfa.id OR sfc.id, + s.itemFk, + i.longName, + i.`size`, + vn.ticketSplitCounter(t.id) counter, + IF(sfa.id OR sfc.id, a.nickname, CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2 FROM tmp.split sp @@ -45688,12 +45692,12 @@ BEGIN item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais - FROM buy b + FROM buy b JOIN tmp.buy tb ON tb.buyFk = b.id JOIN volumeConfig vc JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk - LEFT JOIN temperature t ON t.code = it.temperatureFk + LEFT JOIN temperature t ON t.code = it.temperatureFk GROUP BY Temp; END ;; DELIMITER ; @@ -45713,21 +45717,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - INSERT INTO tmp.buy + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed = vDated AND t.agencyModeFk IN (0, vAgencyFk); CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45746,19 +45750,19 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy + + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk + FROM buy b + JOIN entry e ON e.id = b.entryFk WHERE e.id = vEntryFk; CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45846,12 +45850,12 @@ BEGIN * inserta en tmp.buyRecalc las compras de un awb * * @param awbFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk @@ -45883,7 +45887,7 @@ BEGIN * Recalcula los precios de una compra * * @param vBuyFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc @@ -45914,12 +45918,12 @@ BEGIN * Recalcula los precios de una entrada * * @param vEntryFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b WHERE b.entryFk = vEntryFk; CALL buy_recalcPrices(); @@ -45959,12 +45963,12 @@ BEGIN LIMIT 0; INSERT INTO tBuy(buyFk) - SELECT b.id + SELECT b.id FROM buy b JOIN tmp.ekt t ON t.ektFk = b.ektFk JOIN vn.entry en ON en.id = b.entryFk JOIN vn.travel tr ON tr.id = en.travelFk - JOIN vn.warehouse w ON w.id = tr.warehouseInFk + JOIN vn.warehouse w ON w.id = tr.warehouseInFk JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL'; SELECT b.id buy, i.doPhoto do_photo, b.stickers - b.printedStickers stickersToPrint @@ -45994,24 +45998,24 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT) -BEGIN -/** - * Actualiza el grouping de las últimas compras de un artículo - * - * @param vWarehouseFk Id del almacén - * @param vItemFk Id del Artículo - * @param vGrouping Cantidad de grouping - */ - - CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE()); - - UPDATE vn.buy b - JOIN tmp.buyUltimate bu ON b.id = bu.buyFk - SET b.`grouping` = vGrouping - WHERE bu.warehouseFk = vWarehouseFk - AND bu.itemFk = vItemFk; - - DROP TEMPORARY TABLE tmp.buyUltimate; +BEGIN +/** + * Actualiza el grouping de las últimas compras de un artículo + * + * @param vWarehouseFk Id del almacén + * @param vItemFk Id del Artículo + * @param vGrouping Cantidad de grouping + */ + + CALL vn.buyUltimate(vWarehouseFk, util.VN_CURDATE()); + + UPDATE vn.buy b + JOIN tmp.buyUltimate bu ON b.id = bu.buyFk + SET b.`grouping` = vGrouping + WHERE bu.warehouseFk = vWarehouseFk + AND bu.itemFk = vItemFk; + + DROP TEMPORARY TABLE tmp.buyUltimate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46031,7 +46035,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT) BEGIN /** - * Actualiza packing + * Actualiza packing * * @param vWarehouseFk warehouse del item * @param vItemFk id del item @@ -46041,8 +46045,8 @@ BEGIN UPDATE buy b JOIN tmp.buyUltimate bu ON b.id = bu.buyFk - SET b.packing = vPacking - WHERE bu.warehouseFk = vWarehouseFk + SET b.packing = vPacking + WHERE bu.warehouseFk = vWarehouseFk AND bu.itemFk = vItemFk; DROP TEMPORARY TABLE tmp.buyUltimate; @@ -46081,7 +46085,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vItemFk itemFk; CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -46103,7 +46107,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN +BEGIN /** * Calcula los articulos disponibles y sus precios * @@ -46111,7 +46115,7 @@ BEGIN * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, + * @return tmp.ticketCalculateItem(itemFk, available, producer, * item, size, stems, category, inkFk, image, origin, price) * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) * @return tmp.ticketComponent @@ -46147,22 +46151,22 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; CREATE TEMPORARY TABLE tmp.ticketCalculateItem( - itemFk INT(11) NOT NULL, + itemFk INT(11) NOT NULL, available INT(11), - producer VARCHAR(50), - item VARCHAR(50), - size INT(10) UNSIGNED, - stems INT(11), - category VARCHAR(3), - inkFk VARCHAR(3), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), image VARCHAR(50), - origin VARCHAR(3), + origin VARCHAR(3), price DECIMAL(10,2), priceKg DECIMAL(10,2), `grouping` INT(10) UNSIGNED, PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; - + OPEN cTravelTree; l: LOOP @@ -46184,20 +46188,20 @@ BEGIN bu.buyFk, vZoneFk FROM `cache`.available a - LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id + LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id AND anr.calc_id = vAvailableNoRaidsCalc JOIN tmp.item i ON i.itemFk = a.item_id JOIN vn.item it ON it.id = i.itemFk JOIN vn.`zone` z ON z.id = vZoneFk - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id - LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk - LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk + LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed FROM vn.addressFilter af - JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed - FROM vn.address ad - JOIN vn.province p ON p.id = ad.provinceFk + JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed + FROM vn.address ad + JOIN vn.province p ON p.id = ad.provinceFk WHERE ad.id = vAddressFk ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) @@ -46214,7 +46218,7 @@ BEGIN JOIN vn.itemType itt ON itt.id = it.typeFk JOIN vn.itemCategory itc on itc.id = itt.categoryFk JOIN vn.address ad ON ad.id = vAddressFk - LEFT JOIN vn.clientItemType cit + LEFT JOIN vn.clientItemType cit ON cit.clientFk = ad.clientFk AND cit.itemTypeFk = itt.id LEFT JOIN vn.clientItemCategory cic @@ -46227,7 +46231,7 @@ BEGIN AND (itc.isReclining OR ISNULL(it.`size`) OR it.`size` < z.itemMaxSize OR ISNULL(z.itemMaxSize)) AND NOT (cit.isAllowed <=> FALSE) AND (ISNULL(cic.itemCategoryFk) OR cit.isAllowed); - + DROP TEMPORARY TABLE tmp.buyUltimate; CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); @@ -46308,7 +46312,7 @@ BEGIN * Calcula los componentes de los articulos de tmp.ticketLot * * @param vZoneFk para calcular el transporte - * @param vAddressFk Consignatario + * @param vAddressFk Consignatario * @param vShipped dia de salida del pedido * @param vWarehouseFk warehouse de salida del pedido * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) @@ -46316,15 +46320,15 @@ BEGIN * * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) */ - + DECLARE vClientFk INT; DECLARE vIsFrenchVNHBuyer BOOLEAN DEFAULT FALSE; DECLARE vVNHWarehouseFk INT DEFAULT 7; DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; + FROM address + WHERE id = vAddressFk; SELECT (c.country = 'FRANCIA' AND vWarehouseFk = vVNHWarehouseFk) INTO vIsFrenchVNHBuyer @@ -46338,16 +46342,16 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticketComponentCalculate (PRIMARY KEY (itemFk, warehouseFk)) ENGINE = MEMORY - SELECT - tl.itemFk, - tl.warehouseFk, + SELECT + tl.itemFk, + tl.warehouseFk, tl.available, IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate2, b.price2)),IFNULL(pf.rate2, b.price2)) rate2, IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate3, b.price3)),IFNULL(pf.rate3, b.price3)) rate3, IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, IFNULL(pf.`grouping`, b.`grouping`) `grouping`, ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, + tl.buyFk, i.typeFk, IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping FROM tmp.ticketLot tl @@ -46355,7 +46359,7 @@ BEGIN JOIN item i ON i.id = tl.itemFk JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( @@ -46367,55 +46371,55 @@ BEGIN pf.rate3, zw.warehouseFk FROM priceFixed pf - JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND zw.warehouseFk IN (pf.warehouseFk,0) WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC LIMIT 10000000000000000000 ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.merchandise - AND tl.zoneFk = vZoneFk + AND tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk; -- Coste INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - c2.id, + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc + FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'purchaseValue' JOIN buy b ON b.id = tcc.buyFk; -- Margen INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - c2.id, + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc + FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'margin' JOIN buy b ON b.id = tcc.buyFk; -- Promo Francia IF vIsFrenchVNHBuyer THEN - + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - c2.id, + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, - vFrenchDiscount * (b.buyingValue + b.freightValue + b.packageValue + b.comissionValue) / ( 1 - vFrenchDiscount) - FROM tmp.ticketComponentCalculate tcc + FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'frenchOffer' JOIN buy b ON b.id = tcc.buyFk; - + END IF; DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; @@ -46424,17 +46428,17 @@ BEGIN FROM tmp.ticketComponent tc JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk GROUP BY tc.itemFk, warehouseFk; - + -- RECOBRO INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, tcb.itemFk, c2.id, - ROUND(tcb.base * + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, + ROUND(tcb.base * LEAST( MAX(GREATEST(IFNULL(cr.priceIncreasing,0), IFNULL(cr1.priceIncreasing,0), IFNULL(cr2.priceIncreasing,0)) - ), - cc.maxPriceIncreasingRatio), + ), + cc.maxPriceIncreasingRatio), 3) FROM tmp.ticketComponentBase tcb JOIN vn.component c2 ON c2.code = 'debtCollection' @@ -46452,29 +46456,29 @@ BEGIN SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk JOIN vn.component c2 ON c2.code = 'autoMana' WHERE wm.isPricesModifierActivated HAVING manaAuto <> 0; - + -- Precios especiales INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, c2.id, GREATEST( - IFNULL(ROUND(tcb.base * c2.tax, 4), 0), + IFNULL(ROUND(tcb.base * c2.tax, 4), 0), IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 ) cost FROM tmp.ticketComponentBase tcb JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + 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 JOIN vn.item i ON i.id = tcb.itemFk WHERE sp.value IS NULL AND i.supplyResponseFk IS NULL; - -- Individual + -- Individual INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, @@ -46485,10 +46489,10 @@ BEGIN JOIN vn.client c ON c.id = vClientFk JOIN vn.businessType bt ON bt.code = c.businessTypeFk WHERE bt.code = 'individual'; - + -- Venta por paquetes INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'salePerPackage' JOIN buy b ON b.id = tcc.buyFk @@ -46501,12 +46505,12 @@ BEGIN SELECT vZoneFk id; CALL zone_getOptionsForShipment(vShipped, TRUE); - + -- Reparto INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, + SELECT tcc.warehouseFK, tcc.itemFk, - c2.id, + c2.id, z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / (1000 * vc.standardFlowerBox) , 4) cost FROM tmp.ticketComponentCalculate tcc JOIN item i ON i.id = tcc.itemFk @@ -46515,21 +46519,21 @@ BEGIN JOIN agencyMode am ON am.id = z.agencyModeFk JOIN vn.volumeConfig vc JOIN vn.component c2 ON c2.code = 'delivery' - LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk AND ic.itemFk = tcc.itemFk - HAVING cost <> 0; + HAVING cost <> 0; DROP TEMPORARY TABLE tmp.zoneOption; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY SELECT * FROM tmp.ticketComponent; -- Precio especial INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - c2.id, + SELECT tcc.warehouseFk, + tcc.itemFk, + c2.id, sp.value - SUM(tcc.cost) sumCost FROM tmp.ticketComponentCopy tcc JOIN component c ON c.id = tcc.componentFk @@ -46540,11 +46544,11 @@ BEGIN GROUP BY tcc.itemFk, tcc.warehouseFk HAVING ABS(sumCost) > 0.001; - -- Rappel + -- Rappel INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - IFNULL(c.componentFk ,c2.id), + SELECT tcc.warehouseFk, + tcc.itemFk, + IFNULL(c.componentFk ,c2.id), SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost FROM tmp.ticketComponentCopy tcc JOIN vn.clientChain cc ON cc.clientFk = vClientFk @@ -46565,16 +46569,16 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, + SELECT tcc.warehouseFk, + tcc.itemFk, 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + 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 + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 + 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; @@ -46594,17 +46598,17 @@ BEGIN 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`, + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg + SUM(tcs.sumCost) / weightGrouping priceKg FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 + WHERE IFNULL(tcs.classRate, 3) = 3 GROUP BY tcs.warehouseFk, tcs.itemFk; INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) @@ -46612,14 +46616,14 @@ BEGIN SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000 ) t GROUP BY itemFk, warehouseFk, `grouping`; - + DROP TEMPORARY TABLE tmp.ticketComponentCalculate, tmp.ticketComponentSum, tmp.ticketComponentBase, tmp.ticketComponentRate, tmp.ticketComponentCopy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46638,7 +46642,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; CREATE TEMPORARY TABLE tmp.ticketComponent ( `warehouseFk` INT UNSIGNED NOT NULL, @@ -46648,9 +46652,9 @@ BEGIN INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC) )ENGINE=MEMORY DEFAULT CHARSET=utf8; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( `warehouseFk` INT UNSIGNED NOT NULL, `itemFk` INT NOT NULL, `rate` INT NOT NULL, @@ -46659,7 +46663,7 @@ BEGIN `priceKg` DECIMAL(10,4), INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC) - )ENGINE=MEMORY DEFAULT CHARSET=utf8; + )ENGINE=MEMORY DEFAULT CHARSET=utf8; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46678,7 +46682,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketComponentPrice, tmp.ticketComponent, tmp.ticketLot; @@ -46702,12 +46706,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_test`() 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, + * @return tmp.ticketCalculateItem(itemFk, available, producer, * item, size, stems, category, inkFk, image, origin, price) * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) * @return tmp.ticketComponent @@ -46729,10 +46733,10 @@ proc: BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT 10 itemFk; -- Establece los almacenes y las fechas que van a entrar al disponible -SELECT 1; +SELECT 1; CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); SELECT 2; DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; @@ -46747,25 +46751,25 @@ SELECT 2; KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH ) ENGINE=MEMORY DEFAULT CHARSET=utf8; CALL catalog_componentPrepare(); - + SELECT 3; DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; CREATE TEMPORARY TABLE tmp.ticketCalculateItem( - itemFk INT(11) NOT NULL, + itemFk INT(11) NOT NULL, available INT(11), - producer VARCHAR(50), - item VARCHAR(50), - size INT(10) UNSIGNED, - stems INT(11), - category VARCHAR(3), - inkFk VARCHAR(3), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), image VARCHAR(50), - origin VARCHAR(3), + origin VARCHAR(3), price DECIMAL(10,2), priceKg DECIMAL(10,2), PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; - + OPEN cTravelTree; l: LOOP @@ -46792,35 +46796,35 @@ SELECT 5; LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id WHERE i.calc_id = vAvailableCalc AND i.available > 0; - + DROP TEMPORARY TABLE tmp.buyUltimate; - + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); SELECT 6; INSERT INTO tmp.ticketCalculateItem ( - itemFk, - available, - producer, - item, - size, - stems, - category, + itemFk, + available, + producer, + item, + size, + stems, + category, inkFk, image, origin, price, priceKg) - SELECT - tl.itemFk, + SELECT + tl.itemFk, SUM(tl.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, i.image, - o.code origin, + o.code origin, bl.price, bl.priceKg FROM tmp.ticketLot tl @@ -46828,11 +46832,11 @@ SELECT 6; LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible JOIN origin o ON o.id = i.originFk JOIN ( - SELECT * + SELECT * FROM (SELECT price, itemFk, priceKg FROM tmp.ticketComponentPrice WHERE warehouseFk = vWarehouseFk - ORDER BY (rate = 2) DESC + ORDER BY (rate = 2) DESC LIMIT 10000000000000000000) sub GROUP BY itemFk ) bl ON bl.itemFk = tl.itemFk @@ -46844,8 +46848,8 @@ SELECT 6; CLOSE cTravelTree; DROP TEMPORARY TABLE tmp.item; -SELECT 7; - +SELECT 7; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46893,22 +46897,22 @@ BEGIN DELETE FROM sms WHERE created < v18Month; DELETE FROM saleTracking WHERE created < vOneYearAgo; DELETE FROM ticketTracking WHERE created < v18Month; - DELETE tobs FROM ticketObservation tobs + DELETE tobs FROM ticketObservation tobs JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; DELETE FROM sharingCart where ended < vDateShort; DELETE FROM sharingClient where ended < vDateShort; - DELETE tw.* FROM ticketWeekly tw + DELETE tw.* FROM ticketWeekly tw LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL; DELETE FROM claim WHERE ticketCreated < vFourYearsAgo; DELETE FROM message WHERE sendDate < vDateShort; -- Robert ubicacion anterior de trevelLog comentario para debug - DELETE sc FROM saleChecked sc + DELETE sc FROM saleChecked sc JOIN sale s ON sc.saleFk = s.id WHERE s.created < vDateShort; DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Month; DELETE bm - FROM buyMark bm - JOIN buy b ON b.id = bm.id + FROM buyMark bm + JOIN buy b ON b.id = bm.id JOIN entry e ON e.id = b.entryFk JOIN travel t ON t.id = e.travelFk WHERE t.landed <= vDateShort; @@ -46919,7 +46923,7 @@ BEGIN DELETE FROM printQueue WHERE statusCode = 'printed' AND created < vDateShort; -- Equipos duplicados - DELETE w.* + DELETE w.* FROM workerTeam w JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated FROM workerTeam @@ -46927,13 +46931,13 @@ BEGIN HAVING duplicated ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id; - DELETE sc + DELETE sc FROM saleComponent sc JOIN sale s ON s.id= sc.saleFk JOIN ticket t ON t.id= s.ticketFk WHERE t.shipped < v18Month; - DELETE c + DELETE c FROM vn.claim c JOIN vn.claimState cs ON cs.id = c.claimStateFk WHERE cs.description = "Anulado" AND @@ -46959,7 +46963,7 @@ BEGIN JOIN vn.dms d ON d.id = th.dmsFk SET d.dmsTypeFk = vTrashId; - DELETE th + DELETE th FROM tmp.thermographToDelete tmp JOIN vn.travelThermograph th ON th.id = tmp.id; @@ -46967,12 +46971,12 @@ BEGIN FROM vn.travel t LEFT JOIN vn.entry e ON e.travelFk = t.id WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; - + UPDATE dms d - JOIN dmsType dt ON dt.id = d.dmsTypeFk - SET d.dmsTypeFk = vTrashId + JOIN dmsType dt ON dt.id = d.dmsTypeFk + SET d.dmsTypeFk = vTrashId WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE()); - + -- borrar entradas sin compras DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; CREATE TEMPORARY TABLE tmp.entryToDelete @@ -46984,29 +46988,29 @@ BEGIN DELETE e FROM vn.entry e - JOIN tmp.entryToDelete tmp ON tmp.id = e.id; - + JOIN tmp.entryToDelete tmp ON tmp.id = e.id; + -- borrar de route registros menores a 4 años DROP TEMPORARY TABLE IF EXISTS tmp.routeToDelete; CREATE TEMPORARY TABLE tmp.routeToDelete SELECT * FROM vn.route r - WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); + WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); UPDATE tmp.routeToDelete tmp JOIN vn.dms d ON d.id = tmp.gestdocFk SET d.dmsTypeFk = vTrashId; - DELETE r + DELETE r FROM tmp.routeToDelete tmp JOIN vn.route r ON r.id = tmp.id; -- borrar registros de dua y awb menores a 2 años DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete; CREATE TEMPORARY TABLE tmp.duaToDelete - SELECT * - FROM vn.dua - WHERE operated < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); + SELECT * + FROM vn.dua + WHERE operated < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); UPDATE tmp.duaToDelete tm JOIN vn.dms d ON d.id = tm.gestdocFk @@ -47016,7 +47020,7 @@ BEGIN FROM tmp.duaToDelete tmp JOIN vn.dua d ON d.id = tmp.id; - DELETE FROM vn.awb WHERE created < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); + DELETE FROM vn.awb WHERE created < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); -- Borra los registros de collection y ticketcollection DELETE FROM vn.collection WHERE created < vDateShort; @@ -47027,7 +47031,7 @@ BEGIN DELETE FROM travelLog WHERE creationDate < v3Month; - CALL shelving_clean; + CALL shelving_clean; END ;; DELIMITER ; @@ -47166,76 +47170,76 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `clientCreate`( - vFirstname VARCHAR(50), - vSurnames VARCHAR(50), - vFi VARCHAR(9), - vAddress TEXT, - vPostcode CHAR(5), - vCity VARCHAR(25), - vProvinceFk SMALLINT(5), - vCompanyFk SMALLINT(5), - vPhone VARCHAR(11), - vEmail VARCHAR(255), +CREATE DEFINER=`root`@`localhost` PROCEDURE `clientCreate`( + vFirstname VARCHAR(50), + vSurnames VARCHAR(50), + vFi VARCHAR(9), + vAddress TEXT, + vPostcode CHAR(5), + vCity VARCHAR(25), + vProvinceFk SMALLINT(5), + vCompanyFk SMALLINT(5), + vPhone VARCHAR(11), + vEmail VARCHAR(255), vUserFk INT) -BEGIN -/** - * Create new client - * - */ - DECLARE vPayMethodFk INT DEFAULT 4; - DECLARE vDueDay INT DEFAULT 5; - DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; - DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; - DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE; - DECLARE vMandateTypeFk INT DEFAULT 2; - - INSERT INTO `client` ( - id, - name, - street, - fi, - phone, - email, - provinceFk, - city, - postcode, - socialName, - payMethodFk, - dueDay, - credit, - isTaxDataChecked, - hasCoreVnl, - isEqualizated) - VALUES ( - vUserFk, - CONCAT('TR ', vFirstname, ' ', vSurnames), - vAddress, - TRIM(vFi), - vPhone, - vEmail, - vProvinceFk, - vCity, - vPostcode, - CONCAT(vSurnames, ' ', vFirstname), - vPayMethodFk, - vDueDay, - vDefaultCredit, - vIsTaxDataChecked, - vHasCoreVnl, - FALSE - ) ON duplicate key update - payMethodFk = vPayMethodFk, - dueDay = vDueDay, - credit = vDefaultCredit, - isTaxDataChecked = vIsTaxDataChecked, - hasCoreVnl = vHasCoreVnl, - isActive = TRUE; - - IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN - INSERT INTO mandate (clientFk, companyFk, mandateTypeFk) - VALUES (vUserFk, vCompanyFk, vMandateTypeFk); - END IF; +BEGIN +/** + * Create new client + * + */ + DECLARE vPayMethodFk INT DEFAULT 4; + DECLARE vDueDay INT DEFAULT 5; + DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; + DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; + DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE; + DECLARE vMandateTypeFk INT DEFAULT 2; + + INSERT INTO `client` ( + id, + name, + street, + fi, + phone, + email, + provinceFk, + city, + postcode, + socialName, + payMethodFk, + dueDay, + credit, + isTaxDataChecked, + hasCoreVnl, + isEqualizated) + VALUES ( + vUserFk, + CONCAT('TR ', vFirstname, ' ', vSurnames), + vAddress, + TRIM(vFi), + vPhone, + vEmail, + vProvinceFk, + vCity, + vPostcode, + CONCAT(vSurnames, ' ', vFirstname), + vPayMethodFk, + vDueDay, + vDefaultCredit, + vIsTaxDataChecked, + vHasCoreVnl, + FALSE + ) ON duplicate key update + payMethodFk = vPayMethodFk, + dueDay = vDueDay, + credit = vDefaultCredit, + isTaxDataChecked = vIsTaxDataChecked, + hasCoreVnl = vHasCoreVnl, + isActive = TRUE; + + IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN + INSERT INTO mandate (clientFk, companyFk, mandateTypeFk) + VALUES (vUserFk, vCompanyFk, vMandateTypeFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47261,21 +47265,21 @@ BEGIN */ DECLARE vClientDebt DOUBLE; - + SELECT vn.clientGetDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5); - + CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE); - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5 FROM vn.greuge WHERE clientFk = vClientFk; - - UPDATE vn.client - SET salesPersonFk = NULL + + UPDATE vn.client + SET salesPersonFk = NULL WHERE id = vClientFk; END ;; @@ -47295,46 +47299,46 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clientFreeze`() -BEGIN -/** -* Congela diariamente aquellos clientes que son morosos sin recobro, -* pero que no sean trabajadores, -* y que el riesgo no sea menor que cero -* hasta que no se gire la remesa no se congelan a los clientes de giro -*/ - - DECLARE vIsRemittanced BOOLEAN; - - SELECT id into vIsRemittanced - FROM receipt - WHERE invoiceFk LIKE 'REMESA%' - AND payed > util.firstDayOfMonth(util.VN_CURDATE()) - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT clientFk - FROM bs.defaulter - WHERE created = util.VN_CURDATE() - AND amount; - - CALL clientGetDebt(util.VN_CURDATE()); - - UPDATE client c - JOIN bi.defaulters d ON d.client = c.id AND d.date = util.VN_CURDATE() - JOIN config ON TRUE - LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL - LEFT JOIN payMethod pm ON pm.id = c.payMethodFk - LEFT JOIN tmp.risk rk ON rk.clientFk = c.id - SET c.isFreezed = TRUE, - d.frozened = util.VN_CURDATE() - WHERE (d.amount > config.defaultersMaxAmount - AND rk.risk > 0) - AND c.typeFk = 'normal' - AND r.id IS NULL - AND (vIsRemittanced OR pm.code <> 'bankDraft'); - - DROP TEMPORARY TABLE tmp.clientGetDebt; +BEGIN +/** +* Congela diariamente aquellos clientes que son morosos sin recobro, +* pero que no sean trabajadores, +* y que el riesgo no sea menor que cero +* hasta que no se gire la remesa no se congelan a los clientes de giro +*/ + + DECLARE vIsRemittanced BOOLEAN; + + SELECT id into vIsRemittanced + FROM receipt + WHERE invoiceFk LIKE 'REMESA%' + AND payed > util.firstDayOfMonth(util.VN_CURDATE()) + LIMIT 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT clientFk + FROM bs.defaulter + WHERE created = util.VN_CURDATE() + AND amount; + + CALL clientGetDebt(util.VN_CURDATE()); + + UPDATE client c + JOIN bi.defaulters d ON d.client = c.id AND d.date = util.VN_CURDATE() + JOIN config ON TRUE + LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL + LEFT JOIN payMethod pm ON pm.id = c.payMethodFk + LEFT JOIN tmp.risk rk ON rk.clientFk = c.id + SET c.isFreezed = TRUE, + d.frozened = util.VN_CURDATE() + WHERE (d.amount > config.defaultersMaxAmount + AND rk.risk > 0) + AND c.typeFk = 'normal' + AND r.id IS NULL + AND (vIsRemittanced OR pm.code <> 'bankDraft'); + + DROP TEMPORARY TABLE tmp.clientGetDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47352,15 +47356,15 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clientGetDebt`(vDate DATE) -BEGIN -/** - * Call client_getDebt - * - * @table tmp.clientGetDebt(clientFk) - * @param vDate Fecha maxima de los registros - * @return tmp.risk - */ - CALL vn.client_getDebt(vDate); +BEGIN +/** + * Call client_getDebt + * + * @table tmp.clientGetDebt(clientFk) + * @param vDate Fecha maxima de los registros + * @return tmp.risk + */ + CALL vn.client_getDebt(vDate); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47392,33 +47396,33 @@ BEGIN DECLARE vIssued DATETIME; DECLARE vBalance DOUBLE DEFAULT 0.00; DECLARE cur CURSOR FOR - SELECT - created, - issued, + SELECT + created, + issued, ROUND(amount, 2) AS balance FROM invoiceOut - WHERE clientFk = vClientFk AND companyFk = vCompanyFk - UNION ALL - SELECT - created, - payed, + WHERE clientFk = vClientFk AND companyFk = vCompanyFk + UNION ALL + SELECT + created, + payed, ROUND(-1 * amountPaid, 2) AS balance - FROM receipt + FROM receipt WHERE clientFk = vClientFk AND companyFk = vCompanyFk ORDER BY issued, created; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN cur; - + proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCreated, vIssued, vBalance; IF vDate IS NULL THEN SET vDate=vIssued; END IF; - + IF vDone THEN LEAVE proc; END IF; @@ -47430,66 +47434,66 @@ BEGIN SET vDone = TRUE; END IF; END LOOP; - + CLOSE cur; - - SELECT - issued, - CAST(debtOut AS DECIMAL(10,2)) debtOut, + + SELECT + issued, + CAST(debtOut AS DECIMAL(10,2)) debtOut, CAST(debtIn AS DECIMAL(10,2)) debtIn, - ref, - companyFk, + ref, + companyFk, priority FROM - (SELECT - NULL AS issued, - SUM(amountUnpaid) AS debtOut, - NULL AS debtIn, - 'Saldo Anterior' AS ref, + (SELECT + NULL AS issued, + SUM(amountUnpaid) AS debtOut, + NULL AS debtIn, + 'Saldo Anterior' AS ref, companyFk, - 0 as priority - FROM - (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 + 0 as priority + FROM + (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 FROM invoiceOut - WHERE clientFk = vClientFK - AND issued < vDate - GROUP BY companyFk - - UNION ALL - - SELECT SUM(-1 * amountPaid), companyFk, 0 - FROM receipt - WHERE clientFk = vClientFK - AND payed < vDate - GROUP BY companyFk) AS transactions - GROUP BY companyFk - - UNION ALL - - SELECT - issued, - amount as debtOut, - NULL AS debtIn, + WHERE clientFk = vClientFK + AND issued < vDate + GROUP BY companyFk + + UNION ALL + + SELECT SUM(-1 * amountPaid), companyFk, 0 + FROM receipt + WHERE clientFk = vClientFK + AND payed < vDate + GROUP BY companyFk) AS transactions + GROUP BY companyFk + + UNION ALL + + SELECT + issued, + amount as debtOut, + NULL AS debtIn, ref, companyFk, - 1 - FROM invoiceOut - WHERE clientFk = vClientFK + 1 + FROM invoiceOut + WHERE clientFk = vClientFK AND issued >= vDate - UNION ALL - - SELECT - r.payed, - NULL as debtOut, - r.amountPaid, - r.invoiceFk, + UNION ALL + + SELECT + r.payed, + NULL as debtOut, + r.amountPaid, + r.invoiceFk, r.companyFk, - 0 + 0 FROM receipt r - WHERE r.clientFk = vClientFK - AND r.payed >= vDate) t - INNER JOIN `client` c ON c.id = vClientFK - HAVING debtOut <> 0 OR debtIn <> 0 + WHERE r.clientFk = vClientFK + AND r.payed >= vDate) t + INNER JOIN `client` c ON c.id = vClientFK + HAVING debtOut <> 0 OR debtIn <> 0 ORDER BY issued, priority DESC, debtIn; END ;; DELIMITER ; @@ -47547,13 +47551,13 @@ BEGIN WHERE id = vClientFk; ELSE - + SELECT id INTO vOwner FROM vn.worker WHERE code = vWorkerCode COLLATE utf8_general_ci; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.clientList; CREATE TEMPORARY TABLE tmp.clientList SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale @@ -47565,7 +47569,7 @@ BEGIN AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) AND c.id != vClientFk HAVING monthSale > 100; - + SELECT SUM(monthSale) INTO vTotalSale FROM tmp.clientList; @@ -47576,7 +47580,7 @@ BEGIN SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47597,12 +47601,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientPackagingOverstock`(vClientFk BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; CREATE TEMPORARY TABLE tmp.clientPackagingOverstock - ENGINE = MEMORY - SELECT itemFk, - sum(GotfromClient) - sum(SenttoClient) as devueltos, + ENGINE = MEMORY + SELECT itemFk, + sum(GotfromClient) - sum(SenttoClient) as devueltos, sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados, - LEAST( - sum(GotfromClient) - sum(SenttoClient), + LEAST( + sum(GotfromClient) - sum(SenttoClient), sum(InvoicedtoClient) - sum(InvoicedfromClient) ) as abonables FROM @@ -47610,14 +47614,14 @@ BEGIN SELECT t.*, IF(@month = month, 0, 1) monthEnd, @month := month - FROM + 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, + 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, @@ -47636,11 +47640,11 @@ BEGIN @month := 0 month, t.companyFk FROM sale s - JOIN ticket t on t.id = s.ticketFk - JOIN packaging p ON p.itemFk = s.itemFk + 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 t.shipped > '2017-11-30' AND p.isPackageReturnable UNION ALL SELECT NULL, @@ -47653,7 +47657,7 @@ BEGIN 'Histórico', NULL, NULL - + FROM ticketPackagingStartingStock tps LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk WHERE tps.clientFk = vClientFk @@ -47669,8 +47673,8 @@ BEGIN NULL AS refFk, NULL, t.companyFk - FROM ticketPackaging tp - JOIN ticket t on t.id = tp.ticketFk + 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 @@ -47707,11 +47711,11 @@ BEGIN -- SET vGraceDays = GREATEST(vGraceDays, 90); CALL vn.clientPackagingOverstock(vClientFk,vGraceDays); - + SELECT id INTO vWarehouseFk FROM vn.warehouse WHERE hasConfectionTeam; - + CALL vn.ticket_add( vClientFk ,util.VN_CURDATE() @@ -47724,22 +47728,22 @@ BEGIN ,account.myUser_getId() ,TRUE ,vNewTicket); - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) SELECT vNewTicket, cpo.itemFk, - cpo.abonables, i.longName, p.price FROM tmp.clientPackagingOverstock cpo JOIN vn.item i ON i.id = cpo.itemFk JOIN vn.packaging p ON p.itemFk = cpo.itemFk WHERE cpo.abonables > 0; - + INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity) SELECT vNewTicket, p.id, cpo.abonables FROM tmp.clientPackagingOverstock cpo JOIN vn.packaging p ON p.itemFk = cpo.itemFk WHERE cpo.abonables > 0; - + SELECT vNewTicket; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47777,9 +47781,9 @@ BEGIN 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 + 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; OPEN rs; @@ -47891,7 +47895,7 @@ BEGIN JOIN client c ON c.accountingAccount = lc.account WHERE lc.`date` BETWEEN vDateFrom AND vDateTo )sub - GROUP BY companyFk, clientFk + GROUP BY companyFk, clientFk ) sub1 ON sub1.clientFk = c.id JOIN supplier s ON s.id = sub1.companyFk JOIN company co ON co.id = sub1.companyFk @@ -47932,13 +47936,13 @@ BEGIN SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59'); DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk + CREATE TEMPORARY TABLE tClientRisk ENGINE = MEMORY SELECT cr.clientFk, SUM(cr.amount) amount FROM clientRisk cr JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk GROUP BY cr.clientFk; - + INSERT INTO tClientRisk SELECT c.clientFk, SUM(r.amountPaid) FROM receipt r @@ -47953,7 +47957,7 @@ BEGIN WHERE t.receiptFk IS NULL AND t.status = 'ok' GROUP BY t.clientFk; - + INSERT INTO tClientRisk SELECT t.clientFk, totalWithVat FROM ticket t @@ -47969,7 +47973,7 @@ BEGIN FROM client c JOIN tClientRisk cr ON cr.clientFk = c.id GROUP BY c.id; - + DROP TEMPORARY TABLE tClientRisk; END ;; DELIMITER ; @@ -47993,9 +47997,9 @@ BEGIN DECLARE i INT DEFAULT 0; DECLARE c INT DEFAULT 0; DECLARE maxClientFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmp.client; - + CREATE TEMPORARY TABLE tmp.`client` (id INT AUTO_INCREMENT, clientFk INT, @@ -48003,40 +48007,40 @@ BEGIN PRIMARY KEY(id), UNIQUE KEY clientFk (clientFk)) ENGINE = MEMORY; - + INSERT INTO tmp.client(clientFk) SELECT DISTINCT clientFk FROM vn.invoiceOut WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - + SELECT max(id) INTO maxClientFk FROM tmp.client; - - + + WHILE i < vNumber DO - + SET i = i + 1; - + WHILE c = 0 DO - + SELECT id INTO c FROM tmp.client WHERE id = floor(RAND() * maxClientFk) + 1 AND isSelected = FALSE LIMIT 1; - + END WHILE; - + -- SELECT i, maxClientFk, c; - - UPDATE tmp.client - SET isSelected = TRUE + + UPDATE tmp.client + SET isSelected = TRUE WHERE id = c; - + SET c = 0; - + END WHILE; - + SELECT c.id, c.name FROM tmp.client tc JOIN vn.client c ON c.id = tc.clientFk WHERE isSelected @@ -48113,35 +48117,35 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT) BEGIN DECLARE vLanded DATE; - + SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded FROM vn.cmrConfig; IF vTicketFk THEN - + IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN - + SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk; - + ELSE - + INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead) SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded FROM vn.ticket t - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.address a ON a.id = w.addressFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.address a ON a.id = w.addressFk WHERE t.id = vTicketFk; - + SELECT LAST_INSERT_ID(); - + END IF; - + ELSE - + INSERT INTO vn.cmr(ead) VALUES(vLanded); - + SELECT LAST_INSERT_ID(); - + END IF; END ;; DELIMITER ; @@ -48164,7 +48168,7 @@ BEGIN /** * Insert the monthly CMR summary in vn.mail on the 5th of each month. */ - + SET SESSION group_concat_max_len = 1000000; -- IF (DAY(util.VN_CURDATE()) = 5) THEN INSERT INTO @@ -48192,7 +48196,7 @@ BEGIN CMR Ticket ' - , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), + , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), '

@@ -48210,7 +48214,7 @@ BEGIN -- Actualizamos el estado a 'Enviado' UPDATE vn.cmr c SET c.state = 'Sent' - WHERE c.state = 'Pending' + WHERE c.state = 'Pending' AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH); -- END IF; @@ -48233,7 +48237,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collectionPlacement_get`(vParamFk INT(11), vIsPicker bool) BEGIN /** Devuelve el listado de ubicaciones a las que hay que ir para preparar una colección o ticket - * + * * @param vParamFk Identificador de vn.collection o Identificador de vn.ticket * @param vIsPicker Booleano para distinguer el sacador del revisador */ @@ -48250,7 +48254,7 @@ BEGIN FROM vn.ticketCollection tc JOIN vn.sale s ON s.ticketFk = tc.ticketFk WHERE tc.collectionFk = vParamFk - UNION ALL + UNION ALL SELECT s.ticketFk, s.id, s.itemFk, s.quantity FROM vn.sale s WHERE s.ticketFk = vParamFk; @@ -48275,8 +48279,8 @@ BEGIN (INDEX(itemFk)) ENGINE = MEMORY SELECT b.itemFk, - CASE b.groupingMode - WHEN 0 THEN 1 + CASE b.groupingMode + WHEN 0 THEN 1 WHEN 2 THEN b.packing ELSE b.`grouping` END AS `grouping` @@ -48316,10 +48320,10 @@ BEGIN , st.saleFk as salePreviousPrepared , iss.userFk , ts.quantity - FROM tmp.sale ts - LEFT JOIN (SELECT DISTINCT saleFk + FROM tmp.sale ts + LEFT JOIN (SELECT DISTINCT saleFk FROM vn.saleTracking st - JOIN vn.state s ON s.id = st.stateFk + JOIN vn.state s ON s.id = st.stateFk WHERE st.isChecked AND s.semaphore = 1) st ON st.saleFk = ts.saleFk JOIN vn.itemShelving ish ON ish.itemFk = ts.itemFk @@ -48340,13 +48344,13 @@ BEGIN SELECT saleFk, priority as olderPriority FROM (SELECT saleFk, priority FROM tmp.salePlacementList - ORDER BY isPreviousPrepared DESC, + ORDER BY isPreviousPrepared DESC, itemShelvingSaleFk IS NULL DESC, - visible >= quantity DESC, + visible >= quantity DESC, visible > 0 DESC, IFNULL(shelvingPriority,0) DESC, priority - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) sub GROUP BY saleFk; @@ -48355,7 +48359,7 @@ BEGIN ENGINE MEMORY SELECT s1.saleFk, `order`as saleOrder FROM tmp.salePlacementList s1 - JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; + JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; UPDATE tmp.salePlacementList s1 JOIN tmp.salePlacementList_3 s3 ON s3.saleFk = s1.saleFk @@ -48369,10 +48373,10 @@ BEGIN FROM tmp.salePlacementList spl JOIN vn.sale s ON s.id = spl.saleFk ORDER BY saleOrder, - isPreviousPrepared DESC, + isPreviousPrepared DESC, itemShelvingSaleFk DESC, IF(vIsPicker, visible = 0, TRUE), - s.quantity <= spl.visible DESC, + s.quantity <= spl.visible DESC, shelvingPriority DESC, -- PAK 05/11/2021 priority; @@ -48405,27 +48409,27 @@ BEGIN DECLARE vConcept VARCHAR(50); DECLARE itemFk INT; DECLARE vSaleFk INT default 0; - + DECLARE vDescription VARCHAR(50); DECLARE vItemName VARCHAR(50); - + SELECT barcodeToItem(vItemFk) INTO itemFk; - + SELECT CONCAT(vn.getUser()," ",DATE_FORMAT(util.VN_NOW( ), "%H:%i" )," ",i.name) INTO vConcept FROM vn.item i WHERE i.id = itemFk; - + SELECT name INTO vItemName FROM vn.item WHERE id = vItemFk; SELECT CONCAT("Añadido articulo ", vItemName, " cantidad:", vQuantity) INTO vDescription; - - INSERT INTO vn.ticketLog (originFk, userFk, action , description) + + INSERT INTO vn.ticketLog (originFk, userFk, action , description) VALUES(vTicketFk, vn.getUser(), 'update', vDescription); - + INSERT INTO vn.sale (itemFk,ticketFk,concept,quantity,isAdded) VALUES (itemFk,vTicketFk,vConcept,vQuantity,1); SELECT last_insert_id() INTO vSaleFk; - + CALL vn.sale_calculateComponent(vSaleFk, null); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48443,7 +48447,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(vUserFk INT, OUT vCollectionFk INT) -proc:BEGIN +proc:BEGIN /* Comprueba si existen colecciones libres que se ajustan al perfil del usuario * y le asigna la más antigua. * Añade un registro al semillero de colecciones @@ -48476,14 +48480,14 @@ proc:BEGIN FROM vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id JOIN vn.state s ON s.code = 'PRINTED_AUTO' - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* FROM vn.collection c - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; -- Se a�ade registro al semillero @@ -48493,8 +48497,8 @@ proc:BEGIN -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion SELECT MIN(c.id) INTO vCollectionFk - FROM vn.collection c - JOIN vn.operator o + FROM vn.collection c + JOIN vn.operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) AND o.numberOfWagons = c.wagons AND o.trainFk = c.trainFk @@ -48529,11 +48533,11 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_get`(vWorkerFk INT) BEGIN - + /* Obtiene colección del sacador si tiene líneas pendientes - * + * * @param vWorkerFk id del worker - * + * * @table Devuelve tabla temporal con las colecciones pendientes. */ DROP TEMPORARY TABLE IF EXISTS tCollection; @@ -48541,18 +48545,18 @@ BEGIN CREATE TEMPORARY TABLE tCollection SELECT c.id collectionFk, date(c.created) created - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk JOIN ticketState ts ON ts.ticketFk = tc.ticketFk JOIN state s2 ON s2.id = ts.stateFk JOIN productionConfig pc JOIN vn.state ss on ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk + WHERE c.workerFk = vWorkerFk AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder + AND s2.order < pc.pendingCollectionsOrder GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); @@ -48579,15 +48583,15 @@ BEGIN * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones - */ + */ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + FROM vn.collection WHERE id = vParamFk; - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, @@ -48597,20 +48601,20 @@ BEGIN FROM vn.ticket t LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk + WHERE t.id = vParamFk AND t.shipped >= util.yesterday() UNION ALL - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, @@ -48620,15 +48624,15 @@ BEGIN FROM vn.ticket t JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE tc.collectionFk = vParamFk; @@ -48649,21 +48653,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_kill`(vSelf INT) -BEGIN - - /* Elimina una coleccion y coloca sus tickets en OK - * - */ - - INSERT INTO vncontrol.inter(state_id, Id_Ticket) - SELECT s.id, ticketFk - FROM vn.ticketCollection tc - JOIN vn.state s ON s.code = 'OK' - WHERE tc.collectionFk = vSelf; - - DELETE FROM vn.collection - WHERE id = vSelf; - +BEGIN + + /* Elimina una coleccion y coloca sus tickets en OK + * + */ + + INSERT INTO vncontrol.inter(state_id, Id_Ticket) + SELECT s.id, ticketFk + FROM vn.ticketCollection tc + JOIN vn.state s ON s.code = 'OK' + WHERE tc.collectionFk = vSelf; + + DELETE FROM vn.collection + WHERE id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49121,8 +49125,8 @@ proc:BEGIN -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo DELETE tt.* FROM tTrain tt - LEFT JOIN (SELECT DISTINCT wagon - FROM tTrain + LEFT JOIN (SELECT DISTINCT wagon + FROM tTrain WHERE ticketFk IS NOT NULL ) nn ON nn.wagon = tt.wagon WHERE nn.wagon IS NULL; @@ -49217,7 +49221,7 @@ proc:BEGIN WHERE w.id = vn.getUser(); SELECT COUNT(ws.id) INTO vWagons - FROM workerShelving ws + FROM workerShelving ws WHERE ws.workerFk = vWorkerFk AND ws.collectionFk IS NULL; @@ -49247,7 +49251,7 @@ proc:BEGIN ORDER BY wagon ASC, level ASC; UPDATE vn.ticketCollection tc - JOIN tmp.smartTags ts ON tc.wagon = ts.wagon AND tc.level = ts.level + JOIN tmp.smartTags ts ON tc.wagon = ts.wagon AND tc.level = ts.level SET tc.smartTagFk = ts.code WHERE tc.collectionFk = vCollectionFk; @@ -49294,14 +49298,14 @@ proc:BEGIN DECLARE vTrainFk INT DEFAULT 1; DECLARE vUserFk INT; DECLARE vHourMatters BOOL DEFAULT TRUE; - + SELECT pc.ticketPrintedMax * vWagons, pc.ticketTrolleyMax * vWagons, pc.maxNotReadyCollections INTO vMaxTicketPrinted, vMaxTickets, vMaxNotReadyCollections FROM vn.productionConfig pc; /*IF NOT vn.deviceProductionUser_Exists(vUserFk) THEN - + LEAVE proc; - + END IF;*/ SELECT w.code, w.id INTO vWorkerCode, vUserFk @@ -49313,44 +49317,44 @@ proc:BEGIN INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk FROM vn.sector WHERE id = vSectorFk; -- Hola - + -- Si está habilitado el modo cazador para las motos, y el usuario no esta registrado, se sale. - - IF (SELECT isTractorHuntingMode FROM vn.deviceProductionConfig dpc) AND vItemPackingTypeFk = 'H' THEN - IF (SELECT COUNT(*) FROM vn.workerWithoutTractor wwt WHERE wwt.workerFk = vUserFk) THEN + + IF (SELECT isTractorHuntingMode FROM vn.deviceProductionConfig dpc) AND vItemPackingTypeFk = 'H' THEN + IF (SELECT COUNT(*) FROM vn.workerWithoutTractor wwt WHERE wwt.workerFk = vUserFk) THEN CALL util.throw('Usuario no registrado con moto'); LEAVE proc; END IF; END IF; - - + + -- Si hay colecciones sin terminar, sale del proceso SELECT count(*) INTO vNotReadyCollections FROM ( SELECT count(DISTINCT s.id) totalRow, count(DISTINCT st.id) pickedRow - FROM vn.collection c - JOIN vn.ticketCollection tc ON tc.collectionFk = c.id - JOIN vn.sale s ON s.ticketFk = tc.ticketFk + FROM vn.collection c + JOIN vn.ticketCollection tc ON tc.collectionFk = c.id + JOIN vn.sale s ON s.ticketFk = tc.ticketFk JOIN vn.state ss ON ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st ON st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vUserFk + WHERE c.workerFk = vUserFk AND c.created >= TIMESTAMPADD(HOUR , -6,util.VN_NOW()) AND s.quantity != 0 GROUP BY c.id - HAVING totalRow > pickedRow) sub; + HAVING totalRow > pickedRow) sub; IF vMaxNotReadyCollections < vNotReadyCollections THEN - + CALL util.throw('Hay colecciones pendientes'); LEAVE proc; - + END IF; IF vIsPreviousPrepared THEN CALL util.throw('Es de preparación previa'); LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion - + SELECT id INTO vStateFk FROM vn.state WHERE `code` = 'PREVIOUS_PREPARATION'; @@ -49362,37 +49366,37 @@ proc:BEGIN END IF; - CALL vn.productionControl(vWarehouseFk, 0); + CALL vn.productionControl(vWarehouseFk, 0); -- Esto hay que corregirlo añadiendo un nuevo parámetro al proc. PAK 23/12/21 IF vSectorFk = 65 THEN -- Pedidos pequeños - + SET vTrainFk = 2; - + SET vHourMatters = FALSE; - - DELETE pb.* + + DELETE pb.* FROM tmp.productionBuffer pb - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE pb.m3 * 1000 > vc.minTicketVolume; - + END IF; - -- Se obtiene nº de colección y el buffer con los pedidos preparables + -- Se obtiene nº de colección y el buffer con los pedidos preparables INSERT INTO vn.collection SET workerFk = vUserFk, itemPackingTypeFk = vItemPackingTypeFk, trainFk = vTrainFk; - + SELECT LAST_INSERT_ID() INTO vCollectionFk; - + -- 05/08/2021 PAK Jose Frau pide que los tickets de recogida en Algemesí sólo se saquen si están asignados. DELETE pb.* FROM tmp.productionBuffer pb JOIN vn.state s ON s.id = pb.state WHERE pb.agency = 'REC_ALGEMESI' AND s.code != 'PICKER_DESIGNED'; - + -- 2/3/2022 PAK Se acuerda con Pepe que los pedidos con riesgo no se sacan aunque se asignen. DELETE pb.* FROM tmp.productionBuffer pb @@ -49405,13 +49409,13 @@ proc:BEGIN JOIN vn.state s ON s.id = pb.state WHERE s.code = 'PICKER_DESIGNED' AND pb.workerCode = vWorkerCode; - + IF hasAssignedTickets THEN - - UPDATE vn.collection - SET itemPackingTypeFk = NULL + + UPDATE vn.collection + SET itemPackingTypeFk = NULL WHERE id = vCollectionFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; CREATE TEMPORARY TABLE tmp.ticketToSplit SELECT pb.ticketFk @@ -49419,42 +49423,42 @@ proc:BEGIN JOIN vn.state s ON s.id = pb.state WHERE s.code = 'PICKER_DESIGNED' AND pb.workerCode = vWorkerCode - ORDER BY HH, - mm, - s.`order` DESC, + ORDER BY HH, + mm, + s.`order` DESC, pb.m3 DESC; - - WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO - + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + SELECT MIN(ticketFk) INTO vTicketToSplit FROM tmp.ticketToSplit; - + CALL vn.ticket_splitItemPackingType(vTicketToSplit,IFNULL(vItemPackingTypeFk, 'H')); - + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) SELECT ticketFk, vCollectionFk FROM tmp.ticketIPT - WHERE (itemPackingTypeFk = vItemPackingTypeFk) ; - + WHERE (itemPackingTypeFk = vItemPackingTypeFk) ; + DELETE FROM tmp.ticketToSplit WHERE ticketFk = vTicketToSplit; - + DROP TEMPORARY TABLE tmp.ticketIPT; - + END WHILE; - + CALL vn.productionControl(vWarehouseFk, 0); - + ELSE - + SELECT COUNT(*) INTO vPrintedTickets FROM tmp.productionBuffer pb JOIN vn.state s ON s.id = pb.state JOIN vn.agencyMode am ON am.id = pb.agencyModeFk JOIN vn.agency a ON a.id = am.agencyFk - JOIN vn.productionConfig pc + JOIN vn.productionConfig pc WHERE pb.shipped = util.VN_CURDATE() - AND (pb.ubicacion IS NOT NULL + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND s.isPreparable AND ( @@ -49462,7 +49466,7 @@ proc:BEGIN OR (pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV)) OR (pb.H = 0 AND pb.V = 0 AND pb.N > 0 AND ISNULL(pb.collectionH) AND ISNULL(pb.collectionV)) ) - AND (pc.isPreviousPreparationRequired = FALSE + AND (pc.isPreviousPreparationRequired = FALSE OR pb.previousWithoutParking = FALSE); SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; @@ -49473,16 +49477,16 @@ proc:BEGIN SELECT s2.id, pb.ticketFk, vUserFk FROM tmp.productionBuffer pb JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.agency a ON a.id = am.agencyFk JOIN vn.state s ON s.id = pb.state JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' JOIN vn.ticket t ON t.id = pb.ticketFk JOIN vn.ticketConfig tc JOIN vn.productionConfig pc WHERE pb.shipped = util.VN_CURDATE() - AND (LENGTH(pb.problem) = 0 + AND (LENGTH(pb.problem) = 0 OR (pb.problem = 'PEQUEÑO' AND vTrainFk = 2)) - AND (pb.ubicacion IS NOT NULL + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND s.isPrintable AND s.isOK @@ -49492,23 +49496,23 @@ proc:BEGIN OR (pb.H = 0 AND pb.V = 0 AND pb.N > 0 AND ISNULL(pb.collectionH) AND ISNULL(pb.collectionV)) ) AND t.created < TIMESTAMPADD(MINUTE, - tc.pickingDelay , util.VN_NOW()) - AND (pc.isPreviousPreparationRequired = FALSE + AND (pc.isPreviousPreparationRequired = FALSE OR pb.previousWithoutParking = FALSE) - ORDER BY HH, + ORDER BY HH, mm, s.`order` DESC, pb.m3 DESC LIMIT vMaxTicketPrinted; - + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; CREATE TEMPORARY TABLE tmp.ticketToSplit SELECT pb.ticketFk, (pb.H + pb.V = 0) isNeutral FROM tmp.productionBuffer pb JOIN vn.agencyMode am ON am.id = pb.agencyModeFk - JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.agency a ON a.id = am.agencyFk JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk JOIN vn.state s ON s.id = tst.state JOIN vn.productionConfig pc @@ -49517,46 +49521,46 @@ proc:BEGIN OR (pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV)) OR (pb.H = 0 AND pb.V = 0 AND pb.N > 0 AND ISNULL(pb.collectionH) AND ISNULL(pb.collectionV)) ) - AND (pb.ubicacion IS NOT NULL + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND LENGTH(pb.problem) = 0 AND s.isPreparable - AND (pc.isPreviousPreparationRequired = FALSE + AND (pc.isPreviousPreparationRequired = FALSE OR pb.previousWithoutParking = FALSE) ORDER BY pb.HH, pb.mm, s.`order` DESC LIMIT vMaxTickets; - - WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO - + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + SELECT MIN(ticketFk) INTO vTicketToSplit FROM tmp.ticketToSplit; - - - IF (SELECT isNeutral - FROM tmp.ticketToSplit + + + IF (SELECT isNeutral + FROM tmp.ticketToSplit WHERE ticketFk = vTicketToSplit) THEN - + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) VALUES(vTicketToSplit, vCollectionFk); - + ELSE - + CALL vn.ticket_splitItemPackingType(vTicketToSplit, vItemPackingTypeFk); - + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) SELECT ticketFk, vCollectionFk FROM tmp.ticketIPT WHERE itemPackingTypeFk = vItemPackingTypeFk; - + DROP TEMPORARY TABLE tmp.ticketIPT; - + END IF; - + DELETE FROM tmp.ticketToSplit WHERE ticketFk = vTicketToSplit; - + END WHILE; - + END IF; -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección @@ -49583,20 +49587,20 @@ proc:BEGIN SELECT t.ticketFk, SUM(s.quantity * vc.shelveVolume / i.packingShelve) shelveLiters FROM tmp.ticket t JOIN vn.sale s ON s.ticketFk = t.ticketFk - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.item i ON i.id = s.itemFk JOIN vn.volumeConfig vc - WHERE i.packingShelve + WHERE i.packingShelve GROUP BY t.ticketFk; - UPDATE tmp.ticket t + UPDATE tmp.ticket t JOIN tmp.ticketShelveLiters tsl ON tsl.ticketFk = t.ticketFk SET t.shelveLiters = tsl.shelveLiters; -- Es importante que el primer ticket se coja en todos los casos - + SET vFirstTicketFk = 0; - SELECT ticketFk, HH, mm + SELECT ticketFk, HH, mm INTO vFirstTicketFk, vHour, vMinute FROM tmp.ticket ORDER BY productionOrder DESC, HH, mm @@ -49604,47 +49608,47 @@ proc:BEGIN -- Hay que excluir aquellos que no tengan la misma hora de preparación IF vHourMatters THEN - - DELETE + + DELETE FROM tmp.ticket - WHERE HH != vHour + WHERE HH != vHour OR mm != vMinute; - + END IF; - + -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido -- no es monoticket, excluimos a los de más de un carro IF (SELECT (t.shelveLiters > vc.trolleyM3 * 1000) FROM tmp.ticket t - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE t.ticketFk = vFirstTicketFk) THEN - DELETE - FROM tmp.ticket + DELETE + FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; - + ELSE - + DELETE t.* - FROM tmp.ticket t - JOIN vn.volumeConfig vc + FROM tmp.ticket t + JOIN vn.volumeConfig vc WHERE t.shelveLiters > vc.trolleyM3 * 1000; - + END IF; -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* + DELETE tc.* FROM vn.ticketCollection tc LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND t.ticketFk IS NULL; - + -- Construccion del tren - + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. UPDATE tmp.ticket t JOIN - ( SELECT MAX(i.size) maxHeigth, + ( SELECT MAX(i.size) maxHeigth, tc.ticketFk FROM vn.ticketCollection tc JOIN vn.sale s ON s.ticketFk = tc.ticketFk @@ -49653,11 +49657,11 @@ proc:BEGIN AND tc.collectionFk = vCollectionFk GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk SET t.height = IFNULL(sub.maxHeigth,0); - + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; CREATE TEMPORARY TABLE tmp.wagonsVolumetry - SELECT cv.`level` as shelve, + SELECT cv.`level` as shelve, 1 as wagon, cv.`lines`, cv.liters, @@ -49673,7 +49677,7 @@ proc:BEGIN SET vWagonCounter = vWagonCounter + 1; INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) - SELECT cv.`level` as shelve, + SELECT cv.`level` as shelve, vWagonCounter as wagon, cv.`lines`, cv.liters, @@ -49689,11 +49693,11 @@ proc:BEGIN SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif FROM ( SELECT t.ticketFk, - wv.shelve, + wv.shelve, wv.wagon, t.productionOrder, - CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, - CAST(wv.liters AS SIGNED) - t.shelveLiters as litersDif, + CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, + CAST(wv.liters AS SIGNED) - t.shelveLiters as litersDif, CAST(wv.height AS SIGNED) - t.height as heightDif FROM tmp.wagonsVolumetry wv JOIN tmp.ticket t @@ -49702,14 +49706,14 @@ proc:BEGIN AND litersDif >= 0 AND heightDif >= 0 ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; - + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 FROM tmp.ticket t JOIN tmp.wagonsVolumetry wv GROUP BY t.ticketFk, wv.wagon; - + SET vWagonCounter = 0; WHILE vWagonCounter < vWagons DO @@ -49725,57 +49729,57 @@ proc:BEGIN AND wagon = vWagonCounter ORDER BY heightDif, litersDif, linesDif LIMIT 1; - + ELSE SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk FROM tmp.ticketShelve WHERE wagon = vWagonCounter - ORDER BY heightDif, litersDif, linesDif + ORDER BY heightDif, litersDif, linesDif LIMIT 1; END IF; IF vShelve > 0 THEN - - UPDATE tmp.ticket + + UPDATE tmp.ticket SET shelve = vShelve, wagon = vWagonCounter WHERE ticketFk = vFirstTicketFk; - + DELETE FROM tmp.ticketShelve WHERE ticketFk = vFirstTicketFk OR (shelve = vShelve AND wagon = vWagonCounter); - + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO - + SELECT ticketFk, shelve INTO vTicket, vShelve FROM tmp.ticketShelve WHERE wagon = vWagonCounter LIMIT 1; - - UPDATE tmp.ticket + + UPDATE tmp.ticket SET shelve = vShelve, wagon = vWagonCounter WHERE ticketFk = vTicket; - + DELETE FROM tmp.ticketShelve WHERE ticketFk = vTicket OR (shelve = vShelve AND wagon = vWagonCounter); - + END WHILE; ELSE - - UPDATE tmp.ticket + + UPDATE tmp.ticket SET shelve = 1, wagon = vWagonCounter WHERE ticketFk = vFirstTicketFk; DELETE FROM tmp.ticketShelve WHERE ticketFk = vFirstTicketFk AND wagon != vWagonCounter; - + END IF; END WHILE; @@ -49784,29 +49788,29 @@ proc:BEGIN DELETE FROM tmp.ticket WHERE shelve = 0; -- Elimina los tickets bloqueados que no se van a preparar - DELETE tc.* + DELETE tc.* FROM vn.ticketCollection tc LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND t.ticketFk IS NULL; -- Elimina los tickets que ya estan en otra coleccion - DELETE tc.* + DELETE tc.* FROM vn.ticketCollection tc - JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk + JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND tc2.collectionFk != vCollectionFk; - + -- Actualiza el estado de la colección UPDATE vn.collection c JOIN vn.state st ON st.code = 'ON_PREPARATION' SET c.stateFk = st.id - WHERE c.id = vCollectionFk; + WHERE c.id = vCollectionFk; -- Asigna las bandejas UPDATE vn.ticketCollection tc JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk - SET tc.level = t.shelve, + SET tc.level = t.shelve, tc.wagon = t.wagon, tc.itemCount = t.`lines`, tc.liters = t.shelveLiters; @@ -49814,38 +49818,38 @@ proc:BEGIN -- Actualiza el estado de los tickets INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) SELECT vStateFk, ticketFk, vUserFk - FROM vn.ticketCollection tc + FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - + -- Aviso para la preparacion previa INSERT INTO vn.ticketDown(ticketFk, collectionFk) SELECT tc.ticketFk, tc.collectionFk FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; - IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN CALL vn.sales_mergeByCollection(vCollectionFk); UPDATE vn.collection c - JOIN (SELECT count(*) saleTotalCount , + JOIN (SELECT count(*) saleTotalCount , sum(s.isPicked != 0) salePickedCount FROM vn.ticketCollection tc JOIN vn.sale s ON s.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND s.quantity > 0 - ) sub - SET c.saleTotalCount = sub.saleTotalCount, + ) sub + SET c.saleTotalCount = sub.saleTotalCount, c.salePickedCount = sub.salePickedCount WHERE c.id = vCollectionFk; - - SELECT vCollectionFk; + + SELECT vCollectionFk; ELSE CALL util.throw('No ha sido posible obtener colección'); DELETE FROM vn.collection WHERE id = vCollectionFk; - + END IF; DROP TEMPORARY TABLE @@ -49855,8 +49859,8 @@ proc:BEGIN tmp.wagonsVolumetry, tmp.ticketShelve, tmp.productionBuffer; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49876,7 +49880,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_printSticker`(vSelf INT) BEGIN /** - * Prints a yellow label from a collection or a ticket + * Prints a yellow label from a collection or a ticket * * @param vSelf collection or ticket */ @@ -49885,16 +49889,16 @@ BEGIN SELECT w.labelerFk INTO vPrinterFk FROM worker w WHERE w.id = account.myUser_getId(); CALL report_print( - 'LabelCollection', + 'LabelCollection', vPrinterFk, - account.myUser_getId(), + account.myUser_getId(), JSON_OBJECT('collectionFk', vSelf), 'high' - ); - + ); + INSERT INTO ticketTrolley(ticket, labelCount) SELECT ticketFk, 1 - FROM ticketCollection + FROM ticketCollection WHERE collectionFk = vSelf ON DUPLICATE KEY UPDATE labelCount = labelCount + 1; END ;; @@ -49948,34 +49952,34 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_updateSale`( vStateFk INT, vTicketFk INT) BEGIN - + DECLARE vNumPrepared INT; DECLARE vNumTotal INT; - REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) + REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk,vStateFk); - - UPDATE vn.sale SET isPicked = 1 + + UPDATE vn.sale SET isPicked = 1 WHERE id = vSaleFk; - + SELECT COUNT(s.id) INTO vNumPrepared FROM vn.sale s WHERE s.ticketFk = vTicketFk AND s.isPicked = 1; - + SELECT COUNT(s.id) INTO vNumTotal FROM vn.sale s WHERE s.ticketFk = vTicketFk; - + IF vNumPrepared = vNumTotal THEN - + INSERT INTO vncontrol.inter SET state_id = vStateFk, Id_Ticket = vTicketFk, Id_Trabajador = vWorkerFk; - + CALL vn.collection_update(vTicketFk); - + END IF; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49993,27 +49997,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT) -BEGIN - -DECLARE vCompanyFk INT; - - SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) - INTO vCompanyFk - FROM vn.routeConfig rc - LEFT JOIN userConfig uc ON uc.userFk = workerFk; - - - SELECT - s.name AS name , - s.NIF AS nif , - s.street AS street , - s.city AS city , - s.postCode AS postCode - - FROM vn.company c - JOIN vn.worker w ON w.id = c.workerManagerFk - JOIN vn.supplier s ON s.id = c.id - WHERE c.id = vCompanyFk; +BEGIN + +DECLARE vCompanyFk INT; + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + INTO vCompanyFk + FROM vn.routeConfig rc + LEFT JOIN userConfig uc ON uc.userFk = workerFk; + + + SELECT + s.name AS name , + s.NIF AS nif , + s.street AS street , + s.city AS city , + s.postCode AS postCode + + FROM vn.company c + JOIN vn.worker w ON w.id = c.workerManagerFk + JOIN vn.supplier s ON s.id = c.id + WHERE c.id = vCompanyFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50033,7 +50037,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME) BEGIN - + DECLARE startingMinute INT; TRUNCATE vn.conveyorExpedition; @@ -50050,23 +50054,23 @@ BEGIN conveyorBuildingClassFk) SELECT e.id, e.created, - 10 * p.depth as depth, + 10 * p.depth as depth, 10 * p.width as width, 10 * p.height as height, IFNULL(t.routeFk,am.agencyFk) routeFk, hour(e.created) * 60 + minute(e.created), IFNULL(et.description , a.name), IFNULL(t.routeFk,am.agencyFk) criterion, - IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) + IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.packaging p ON p.id = e.packagingFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk - JOIN vn.packagingConfig pc + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded AND p.height < 140 @@ -50075,8 +50079,8 @@ BEGIN SELECT MIN(productionMinute) INTO startingMinute FROM vn.conveyorExpedition ce ; - - UPDATE vn.conveyorExpedition + + UPDATE vn.conveyorExpedition SET productionMinute = productionMinute - startingMinute; END ;; @@ -50145,7 +50149,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT) BEGIN - + UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk; END ;; @@ -50168,52 +50172,52 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `crypt`(vText VARCHAR(255), vKey VAR BEGIN DECLARE vEncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vEncryptedChar VARCHAR(1); DECLARE vEncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - + DECLARE vInvalidadChars VARCHAR(255) DEFAULT ''; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar)); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition; - + IF vEncryptedCharPosition > vChainLength THEN - + SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength; - + END IF; - + SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1); - + SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText); @@ -50238,49 +50242,49 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey BEGIN DECLARE vUncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vUncryptedChar VARCHAR(1); DECLARE vUncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition; - + IF vUncryptedCharPosition < 1 THEN - + SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength; - + END IF; - + SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1); - + SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = vUncryptedText; @@ -50376,7 +50380,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -50387,11 +50391,11 @@ BEGIN 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, '/'), @@ -50446,7 +50450,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM department_recalc; - + IF vIsChanged THEN UPDATE department_recalc SET isChanged = FALSE; CALL vn.department_calcTree; @@ -50470,18 +50474,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`() -BEGIN - -/** - * Obtiene los sectores a los cuales les ponemos errores - * - */ - - SELECT id, name - FROM department - WHERE hasToMistake <> FALSE; - - +BEGIN + +/** + * Obtiene los sectores a los cuales les ponemos errores + * + */ + + SELECT id, name + FROM department + WHERE hasToMistake <> FALSE; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50540,19 +50544,19 @@ BEGIN 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; @@ -50590,18 +50594,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceLog_add`(vWorkerFk INT, vAppName VARCHAR(45), vAppVersion VARCHAR(45), vAndroid_id VARCHAR(100)) -BEGIN -/* - * Inserta registro en tabla devicelog el log del usuario conectado - * @param vAppName es el nombre de la app - * @param vAppVersion es la versión de la app - * @param vAndroid_id es el android_id del dispositivo que se ha logueado - */ - - INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id) - VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_id); - - +BEGIN +/* + * Inserta registro en tabla devicelog el log del usuario conectado + * @param vAppName es el nombre de la app + * @param vAppVersion es la versión de la app + * @param vAndroid_id es el android_id del dispositivo que se ha logueado + */ + + INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id) + VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_id); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50620,12 +50624,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT) BEGIN - + /* SELECT COUNT(*) AS UserExists - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu WHERE dpu.userFk = vUserFk;*/ SELECT TRUE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50671,18 +50675,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProduction_getnameDevice`(vAndroid_id VARCHAR(50)) -BEGIN -/** - * Selecciona el id del dispositivo que corresponde al vAndroid_id - * - * @param vAndroid_id el número android_id del dispositivo - * - */ - - SELECT dp.id - FROM deviceProduction dp - WHERE dp.android_id = vAndroid_id; - +BEGIN +/** + * Selecciona el id del dispositivo que corresponde al vAndroid_id + * + * @param vAndroid_id el número android_id del dispositivo + * + */ + + SELECT dp.id + FROM deviceProduction dp + WHERE dp.android_id = vAndroid_id; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50701,10 +50705,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50)) BEGIN - + /* * Comprueba si está registrado el dispositivo mediante su androidId - * + * * @param vUSerFk el id del user * @param vAndroidID es el identificador android_id del dispositivo */ @@ -50716,20 +50720,20 @@ BEGIN SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed FROM vn.deviceProductionConfig dpc; - IF NOT vIsAllUsersAllowed THEN - + IF NOT vIsAllUsersAllowed THEN + SELECT COUNT(*) INTO vIsDepartment - FROM vn.workerDepartment dp + FROM vn.workerDepartment dp JOIN department d ON d.id = dp.departmentFk WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin; - + IF vIsDepartment THEN SELECT COUNT(*) INTO vIsAuthorized - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk WHERE dpu.userFk = vUserFk AND dp.android_id = vAndroidID; - + IF NOT vIsAuthorized THEN SET vMessage = 'Usuario no autorizado'; END IF; @@ -50759,15 +50763,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT) BEGIN UPDATE duaEntry de - JOIN + JOIN ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total FROM buy b JOIN duaEntry de ON de.entryFk = b.entryFk WHERE duaFk = vDuaFk GROUP BY b.entryFk ) sub ON sub.entryFk = de.entryFk - - LEFT JOIN + + LEFT JOIN (SELECT e.id, sum(iit.taxableBase) as euros FROM entry e JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk @@ -50775,11 +50779,11 @@ BEGIN WHERE de.duaFk = vDuaFk GROUP BY e.id ) sub2 ON sub2.id = de.entryFk - + SET de.value = sub.total, de.euroValue = sub2.euros WHERE duaFk = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50803,7 +50807,7 @@ BEGIN DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; DECLARE vCounter INT DEFAULT 0; - + DECLARE rs CURSOR FOR SELECT e.invoiceInFk FROM entry e @@ -50816,7 +50820,7 @@ BEGIN 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 @@ -50828,41 +50832,41 @@ BEGIN 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 vn2008.XDiario x JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN SET x.ASIEN = vASIEN; - + ELSE - + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; - + END IF; - + SET vCounter = vCounter + 1; - + FETCH rs INTO vInvoiceFk; END WHILE; - + CLOSE rs; - - UPDATE dua + + UPDATE dua SET ASIEN = vASIEN WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50888,9 +50892,9 @@ BEGIN SELECT awbFk,companyFk FROM dua WHERE id = vDuaFk; - + SELECT LAST_INSERT_ID() INTO vNewDuaFk; - + INSERT INTO duaEntry(duaFk, entryFk, value, customsValue) SELECT vNewDuaFk, entryFk, value, value - customsValue FROM duaEntry @@ -50919,29 +50923,29 @@ BEGIN DECLARE vBookDated DATE; DECLARE vDiff DECIMAL(10,2); DECLARE vApunte BIGINT; - + SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated - FROM dua + FROM dua WHERE id = vDuaFk; - + IF vBookNumber IS NULL OR NOT vBookNumber THEN CALL ledger_next(vBookNumber); END IF; - + -- Apunte de la aduana INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONCEPTO, + CONCEPTO, EUROHABER, SERIE, empresa_id, CLAVE, FACTURA) - SELECT + SELECT vBookNumber, d.bookEntried, '4700000999', @@ -50954,20 +50958,20 @@ BEGIN FROM duaTax dt JOIN dua d ON d.id = dt.duaFk WHERE dt.duaFk = vDuaFk; - + -- Apuntes por tipo de IVA y proveedor - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, FECHA_EX, FECHA_OP, @@ -50987,17 +50991,17 @@ BEGIN FECREGCON ) - SELECT + SELECT vBookNumber ASIEN, vBookDated FECHA, tr.account SUBCTA, '4330002067' CONTRA, sum(dt.tax) EURODEBE, - sum(dt.base) BASEEURO, + sum(dt.base) BASEEURO, CONCAT('DUA nº',d.code) CONCEPTO, d.id FACTURA, dt.rate IVA, - '*' AUXILIAR, + '*' AUXILIAR, 'D' SERIE, d.issued FECHA_EX, d.operated FECHA_OP, @@ -51024,10 +51028,10 @@ BEGIN WHERE ta.effectived <= vBookDated AND taxAreaFk = 'WORLD' ORDER BY ta.effectived DESC - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) tba GROUP BY rate - ) tr ON tr.rate = dt.rate + ) tr ON tr.rate = dt.rate JOIN supplier s ON s.id = d.companyFk WHERE d.id = vDuaFk GROUP BY dt.rate; @@ -51035,16 +51039,16 @@ BEGIN SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte FROM XDiario WHERE ASIEN = vBookNumber; - + UPDATE XDiario SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, - EURODEBE = EURODEBE - vDiff + EURODEBE = EURODEBE - vDiff WHERE id = vApunte; - + UPDATE dua SET ASIEN = vBookNumber WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51065,21 +51069,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT) BEGIN /** * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry - * + * * @param vDuaFk Id del dua a recalcular **/ DELETE FROM duaTax WHERE duaFk = vDuaFk; - - INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) + + INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base FROM intrastat ist JOIN (SELECT - e.supplierFk, + e.supplierFk, i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id @@ -51087,15 +51091,15 @@ BEGIN ( SELECT i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk GROUP BY i.intrastatFk - + ) tei ON tei.intrastatFk = i.intrastatFk - JOIN + JOIN ( SELECT intrastatFk, sum(amount) as amount FROM duaIntrastat @@ -51104,7 +51108,7 @@ BEGIN ) di ON di.intrastatFk = i.intrastatFk WHERE de.duaFk = vDuaFk GROUP BY e.supplierFk, i.intrastatFk - HAVING Base + HAVING Base ) sub ON ist.id = sub.intrastatFk GROUP BY ist.taxClassFk, sub.supplierFk; END ;; @@ -51124,15 +51128,15 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`() -BEGIN - - INSERT IGNORE INTO vn.genus(name) - SELECT latin_genus_name - FROM edi.genus ; - - INSERT IGNORE INTO vn.specie(name) - SELECT LCASE(latin_species_name) - FROM edi.specie ; +BEGIN + + INSERT IGNORE INTO vn.genus(name) + SELECT latin_genus_name + FROM edi.genus ; + + INSERT IGNORE INTO vn.specie(name) + SELECT LCASE(latin_species_name) + FROM edi.specie ; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51171,71 +51175,71 @@ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur1; read_loop: LOOP - + SET done = FALSE; SET vEntryFk = 0; - + FETCH cur1 INTO vId; - + IF done THEN LEAVE read_loop; END IF; - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk AND ea.supplierFk = e.supplierFk WHERE ea.id = vId AND tr.landed = vLanded LIMIT 1; - + IF NOT vEntryFk THEN - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded AND ea.supplierFk IS NULL LIMIT 1; - + END IF; - + IF NOT vEntryFk THEN - + SET vTravelFk = 0; - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded; - + IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk - FROM vn.ektEntryAssign + FROM vn.ektEntryAssign WHERE id = vId; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyFk WHERE ea.id = vId AND tr.landed = vLanded; - + END IF; - + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk) SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id FROM vn.supplier s @@ -51243,13 +51247,13 @@ OPEN cur1; JOIN vn.currency cu ON cu.code = 'EUR' JOIN vn.ektEntryAssign ea ON ea.id = vId WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - + END IF; - + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vId; @@ -51257,7 +51261,7 @@ OPEN cur1; END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51277,18 +51281,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT) BEGIN DECLARE vConsumption INT; - + SELECT consumption INTO vConsumption FROM energyInput WHERE input = vInput; - INSERT INTO vn.energyMeter - SET - `input` = vInput, - `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), + INSERT INTO vn.energyMeter + SET + `input` = vInput, + `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), `activeTime` = vActiveTime, `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2)) - ON DUPLICATE KEY UPDATE + ON DUPLICATE KEY UPDATE `activeTime` = `activeTime` + vActiveTime, `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2)); END ;; @@ -51311,28 +51315,28 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entryDelivered`(vDated DATE, vEntry BEGIN DECLARE vTravelFk INT; - + SELECT travelFk INTO vTravelFk - FROM vn.entry + FROM vn.entry WHERE id = vEntryFk; - + IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN - + UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated WHERE id = vTravelFk; - + ELSE - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived) SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE FROM vn.travel WHERE id = vTravelFk; - + SELECT LAST_INSERT_ID() INTO vTravelFk; - - UPDATE vn.entry - SET travelFk = vTravelFk + + UPDATE vn.entry + SET travelFk = vTravelFk WHERE id = vEntryFk; - + END IF; END ;; @@ -51361,7 +51365,7 @@ BEGIN WHERE b.entryFk = vEntryFk; CALL vn.ticket_recalcComponents(vTicketFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51385,29 +51389,29 @@ BEGIN DECLARE vEntry INT; DECLARE vBucket VARCHAR(10); DECLARE vSupplierFk INT; - + SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963); -- seleccionamos travel SELECT t.id, e.id INTO vTravel, vEntry FROM travel t LEFT JOIN entry e ON t.id = e.travelFk - WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk - LIMIT 1; - + LIMIT 1; + -- creamos el travel si es necesario IF IFNULL(vTravel, FALSE) = FALSE THEN INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk) VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse); SELECT LAST_INSERT_ID() INTO vTravel; END IF; - + -- creamos la Entrada si es necesario IF IFNULL(vEntry, FALSE) = FALSE THEN INSERT INTO entry (supplierFk, travelFk) VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' SELECT LAST_INSERT_ID() INTO vEntry; END IF; - + -- creamos el cubo si es necesario SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; IF vBucket IS NULL THEN @@ -51417,7 +51421,7 @@ BEGIN SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; END IF; - INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) SELECT itemFk, quantity, vEntry, @@ -51654,7 +51658,7 @@ BEGIN -- Obtiene fecha de llegada y almacén entrante - SELECT landed, warehouseInFk INTO vLanded, vWarehouseFk + SELECT landed, warehouseInFk INTO vLanded, vWarehouseFk FROM vn.travel t JOIN vn.entry e ON t.id = e.travelFk WHERE e.id = vEntry; @@ -51667,13 +51671,13 @@ BEGIN SELECT * FROM ( SELECT * FROM - ( + ( SELECT rate0, rate1, rate2, rate3 FROM vn.rate WHERE dated <= vLanded AND warehouseFk = vWarehouseFk ORDER BY dated DESC - + ) sub UNION ALL SELECT rate0, rate1, rate2, rate3 @@ -51727,14 +51731,14 @@ BEGIN SET e.travelFk = vNewTravelFk, e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')) WHERE e.id = vNewEntryFk; - + IF vChangeEntry THEN UPDATE buy b SET b.entryFk = vNewEntryFk WHERE b.printedStickers = 0 AND b.entryFk = vSelf; END IF; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -51780,7 +51784,7 @@ BEGIN FROM buy b WHERE b.entryFk = vSelf AND b.printedStickers != b.stickers; - + IF vChangeEntry THEN UPDATE buy SET stickers = printedStickers, @@ -51792,7 +51796,7 @@ BEGIN FROM item i WHERE i.description = 'MISFIT' LIMIT 1; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -51867,11 +51871,11 @@ BEGIN description = CONCAT('Se ha creado la entrada ', vNewEntryFk,' transferida desde la ', vSelf), userFk = account.myUser_getId(), originFk = vNewEntryFk; - + UPDATE entry SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1) WHERE id = vNewEntryFk; - + INSERT INTO duaEntry (duaFk, entryFk) SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1; END ;; @@ -51945,12 +51949,12 @@ BEGIN */ DECLARE v_done BOOL DEFAULT FALSE; DECLARE vEntryFk INTEGER; - + DECLARE vCur CURSOR FOR SELECT id FROM tmp.recalcEntryCommision; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; OPEN vCur; @@ -51961,7 +51965,7 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + CALL vn2008.buy_tarifas_entry(vEntryFk); END LOOP; @@ -51986,7 +51990,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk BEGIN /** * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula - * + * * @param vShelvingFk Identificador de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino @@ -51996,49 +52000,49 @@ BEGIN DECLARE buyStickers INT; DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE cur CURSOR FOR + DECLARE cur CURSOR FOR SELECT bb.id buyFk, FLOOR(ish.visible / ish.packing) AS ishStickers, bb.stickers buyStickers FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk AND bb.stickers >= FLOOR(ish.visible / ish.packing) WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci GROUP BY ish.id; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, + + -- Cantidades de la matrícula que exceden la de las entradas + SELECT ish.itemFk, + i.longName, FLOOR(ish.visible / ish.packing) AS etiEnMatricula, bb.stickers etiEnEntrada FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN vn.item i ON i.id = ish.itemFk + LEFT JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) GROUP BY ish.id; - + OPEN cur; read_loop: LOOP SET vDone = FALSE; - + FETCH cur INTO vBuyFk, ishStickers, buyStickers; - + IF vDone THEN LEAVE read_loop; END IF; - + IF ishStickers = buyStickers THEN UPDATE vn.buy SET entryFk = vToEntryFk @@ -52046,9 +52050,9 @@ BEGIN ELSE UPDATE vn.buy SET stickers = stickers - ishStickers, - quantity = stickers * packing + quantity = stickers * packing WHERE id = vBuyFk; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, @@ -52106,7 +52110,7 @@ BEGIN itemOriginalFk FROM vn.buy WHERE id = vBuyFk; - + END IF; END LOOP; @@ -52128,36 +52132,36 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT) -BEGIN - - /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original - * a la nueva - */ - - DECLARE vNewEntryFk INT; - DECLARE vBuyFk INT; - - SELECT MAX(b.id) INTO vBuyFk - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - WHERE b.entryFk = vSelf - AND i.description = 'MISFIT'; - - INSERT INTO vn.entry(supplierFk, dated, notes, travelFk, currencyFk, companyFk) - SELECT supplierFk, dated, CONCAT('E:',vSelf), travelFk, currencyFk, companyFk - FROM vn.entry e - WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - - UPDATE vn.buy b - SET b.entryFk = vNewEntryFk - WHERE b.entryFk = vSelf - AND b.id > vBuyFk; - - SELECT vNewEntryFk; - - +BEGIN + + /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original + * a la nueva + */ + + DECLARE vNewEntryFk INT; + DECLARE vBuyFk INT; + + SELECT MAX(b.id) INTO vBuyFk + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + WHERE b.entryFk = vSelf + AND i.description = 'MISFIT'; + + INSERT INTO vn.entry(supplierFk, dated, notes, travelFk, currencyFk, companyFk) + SELECT supplierFk, dated, CONCAT('E:',vSelf), travelFk, currencyFk, companyFk + FROM vn.entry e + WHERE e.id = vSelf; + + SET vNewEntryFk = LAST_INSERT_ID(); + + UPDATE vn.buy b + SET b.entryFk = vNewEntryFk + WHERE b.entryFk = vSelf + AND b.id > vBuyFk; + + SELECT vNewEntryFk; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52185,7 +52189,7 @@ BEGIN * @param vAction Accion que se quiere añadir * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta - */ + */ DECLARE vDepartment VARCHAR(255); CASE @@ -52236,7 +52240,7 @@ BEGIN WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment GROUP BY cd.workerFk; - + CREATE OR REPLACE TEMPORARY TABLE volume ENGINE = MEMORY SELECT SUM(w.volume) volume, @@ -52247,15 +52251,15 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE errorsByChecker ENGINE = MEMORY - SELECT sub1.workerFk, COUNT(id) errors + SELECT sub1.workerFk, COUNT(id) errors FROM ( SELECT st.workerFk, t.id FROM saleMistake sm JOIN saleTracking st ON sm.saleFk = st.saleFk JOIN vncontrol.accion a ON a.accion_id = st.actionFk - JOIN sale s ON s.id = sm.saleFk - JOIN ticket t on t.id = s.ticketFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND a.accion = vAction GROUP BY s.ticketFk @@ -52267,13 +52271,13 @@ BEGIN SELECT COUNT(t.id) errors, e.workerFk FROM vn.expeditionMistake pm - JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.expedition e ON e.id = pm.expeditionFk JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo GROUP BY e.workerFk; IF (vDepartment = 'Sacadores') THEN - + INSERT INTO errorProduction(userFk, firstname, lastname, @@ -52306,12 +52310,12 @@ BEGIN LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores FROM vn.collection c - JOIN vn.state s ON s.id = c.stateFk + JOIN vn.state s ON s.id = c.stateFk JOIN vn.train tn ON tn.id = c.trainFk - JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.worker w ON w.id = c.workerFk WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id GROUP BY w.id; - + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores ENGINE = MEMORY SELECT COUNT(c.ticketFk) errors, @@ -52331,7 +52335,7 @@ BEGIN JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk SET ep.error = ep.error + ipe.errors WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; - + DROP TEMPORARY TABLE itemPickerErrors; ELSE INSERT INTO errorProduction(userFk, @@ -52367,7 +52371,7 @@ BEGIN LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk GROUP BY w.id; END IF; - + DROP TEMPORARY TABLE total, errorsByClaim, volume, @@ -52393,7 +52397,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`() BEGIN DECLARE vDatedFrom DATETIME; DECLARE vDatedTo DATETIME; - + SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo); @@ -52424,7 +52428,7 @@ BEGIN DECLARE vRouteFk INT DEFAULT 0; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition exp + FROM vn.expedition exp INNER JOIN ticket t on t.id = exp.ticketFk WHERE exp.id = vExpeditionFk; @@ -52514,22 +52518,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vSelf expeditioPallet id. */ DECLARE vPrinterFk INT; - + SELECT w.labelerFk INTO vPrinterFk FROM worker w WHERE w.id = account.myUser_getId(); CALL vn.report_print( - 'LabelPalletExpedition', + 'LabelPalletExpedition', vPrinterFk, account.myUser_getId(), JSON_OBJECT('palletFk',vSelf), 'high' - ); + ); UPDATE vn.expeditionPallet SET isPrint = TRUE WHERE id = vSelf; END ;; @@ -52583,22 +52587,22 @@ BEGIN DECLARE vTotal INT DEFAULT 0; IF vPalletFk = 0 THEN -- Nuevo pallet - - INSERT INTO vn.expeditionPallet(truckFk) + + INSERT INTO vn.expeditionPallet(truckFk) VALUES(vTruckFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END IF; - + SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk; - + IF vTotal <> 0 THEN - SELECT expeditionFk, + SELECT expeditionFk, palletFk - FROM vn.expeditionScan + FROM vn.expeditionScan WHERE palletFk = vPalletFk; - ELSE + ELSE SELECT 0 expeditionFk,vPalletFk palletFk; END IF; END ;; @@ -52671,12 +52675,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT) BEGIN - - REPLACE vn.expeditionScan(expeditionFk, palletFk) + + REPLACE vn.expeditionScan(expeditionFk, palletFk) VALUES(vExpeditionFk, vPalletFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52694,33 +52698,33 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100)) -BEGIN - - /** - * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro - * - * @param vParam Identificador de vn.expedition o de vn.route - * @param vStateCode Corresponde a vn.expeditionStateType.code - */ - - IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT e.id, est.id - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.expeditionStateType est ON est.code = vStateCode - WHERE t.routeFk = vParam; - - ELSE - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT vParam, est.id - FROM vn.expeditionStateType est - WHERE est.code = vStateCode; - - END IF; - +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro + * + * @param vParam Identificador de vn.expedition o de vn.route + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT e.id, est.id + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.expeditionStateType est ON est.code = vStateCode + WHERE t.routeFk = vParam; + + ELSE + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT vParam, est.id + FROM vn.expeditionStateType est + WHERE est.code = vStateCode; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52738,23 +52742,23 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByAdress`(vAdressFk INT, vRouteFk INT, vStateCode VARCHAR(100)) -BEGIN - - /** - * Inserta nuevos registros en la tabla vn.expeditionState - * - * @param vAdressFk Identificador de vn.ticket - * @param vRouteFk Identificador de vn.route - * @param vStateCode Corresponde a vn.expeditionStateType.code - */ - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT e.id, est.id - FROM vn.expedition e - JOIN vn.expeditionStateType est ON est.code = vStateCode - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; - +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState + * + * @param vAdressFk Identificador de vn.ticket + * @param vRouteFk Identificador de vn.route + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT e.id, est.id + FROM vn.expedition e + JOIN vn.expeditionStateType est ON est.code = vStateCode + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52772,20 +52776,20 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100)) -BEGIN - - /** - * Inserta nuevos registros en la tabla vn.expeditionState - * - * @param vExpeditionFk Identificador de vn.expedition - * @param vStateCode Corresponde a vn.expeditionStateType.code - */ - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT vExpeditionFk, est.id - FROM vn.expeditionStateType est - WHERE est.code = vStateCode; - +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState + * + * @param vExpeditionFk Identificador de vn.expedition + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT vExpeditionFk, est.id + FROM vn.expeditionStateType est + WHERE est.code = vStateCode; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52806,7 +52810,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalle BEGIN /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vPalletFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ @@ -52823,7 +52827,7 @@ BEGIN IF NOT hasExpeditions THEN DROP TEMPORARY TABLE tExpeditionScan; - CALL util.throw('palletDoesNotExist'); + CALL util.throw('palletDoesNotExist'); END IF; INSERT INTO vn.expeditionState(expeditionFk, typeFk) @@ -52847,22 +52851,22 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100)) -BEGIN - - /** - * Inserta nuevos registros en la tabla vn.expeditionState, por rutas - * - * @param vRouteFk Identificador de vn.route - * @param vStateCode Corresponde a vn.expeditionStateType.code - */ - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT e.id, est.id - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.expeditionStateType est ON est.code = vStateCode - WHERE t.routeFk = vRouteFk; - +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState, por rutas + * + * @param vRouteFk Identificador de vn.route + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT e.id, est.id + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.expeditionStateType est ON est.code = vStateCode + WHERE t.routeFk = vRouteFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52904,8 +52908,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() BEGIN - SELECT id truckFk, - ETD, + SELECT id truckFk, + ETD, description Destino FROM vn.expeditionTruck WHERE ETD BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -52949,7 +52953,7 @@ BEGIN JOIN address a ON t.addressFk = a.id JOIN route r ON r.id = t.routeFk LEFT JOIN warehouse w ON t.warehouseFk = w.id - LEFT JOIN (SELECT sub.ticketFk, + LEFT JOIN (SELECT sub.ticketFk, CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items FROM ticket t @@ -52980,7 +52984,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT) BEGIN - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -52990,24 +52994,24 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -53021,17 +53025,17 @@ BEGIN vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53050,12 +53054,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT) BEGIN - + /* Devuelve una "ficha" con todos los datos relativos a la expedición - * - * param vExpeditionFk + * + * param vExpeditionFk */ - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -53066,34 +53070,34 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasLeidasSorter - FROM srt.expedition e + FROM srt.expedition e JOIN vn.expedition ve ON ve.id = e.id LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id - JOIN vn.ticket t ON t.id = ve.ticketFk + JOIN vn.ticket t ON t.id = ve.ticketFk WHERE t.routeFk = vRouteFk AND e.created != e.updated - AND ISNULL(es.expeditionFk); - - + AND ISNULL(es.expeditionFk); + + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -53108,17 +53112,17 @@ BEGIN vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas, vEtiquetasLeidasSorter AS etiquetasSorter - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53139,14 +53143,14 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `faultsReview`(vWarehouseFk INT) BEGIN DECLARE vCalcVisibleFk INT; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT iss.itemFk, i.size, i.subName producer, @@ -53159,7 +53163,7 @@ BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE iss.warehouseFk = vWarehouseFk GROUP BY iss.itemFk; - + SELECT ishr.*, sub.longName, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, CAST(sub.fault AS DECIMAL(10,0)) as faltas @@ -53174,7 +53178,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk ) sub ON sub.itemFk = ishr.itemFk ; - + END ;; DELIMITER ; @@ -53248,81 +53252,81 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) -BEGIN - - DECLARE vSijsnerClientFk INT DEFAULT 19752; - - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - - SET vDateStart = vFromDated; - SET vDateEnd = util.Dayend(vToDated); - - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, - CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo - FROM vn.packaging p - LEFT JOIN ( - SELECT FustCode, sum(fustQuantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub - GROUP BY FustCode) sent ON sent.FustCode = p.id - LEFT JOIN ( - SELECT FustCode, sum(quantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA' - AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub - GROUP BY FustCode) tp ON tp.FustCode = p.id - LEFT JOIN ( - SELECT FustCode, sum(quantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub - GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks - OR tp.stucks - OR sj.stucks; - +BEGIN + + DECLARE vSijsnerClientFk INT DEFAULT 19752; + + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + + SET vDateStart = vFromDated; + SET vDateEnd = util.Dayend(vToDated); + + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo + FROM vn.packaging p + LEFT JOIN ( + SELECT FustCode, sum(fustQuantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packageFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub + GROUP BY FustCode) sent ON sent.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA' + AND t.clientFk != vSijsnerClientFk + AND tp.quantity > 0) sub + GROUP BY FustCode) tp ON tp.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub + GROUP BY FustCode) sj ON sj.FustCode = p.id + WHERE sent.stucks + OR tp.stucks + OR sj.stucks; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53340,38 +53344,38 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE) -BEGIN - - DECLARE vSijsnerClientFk INT DEFAULT 19752; - - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - - SET vDateStart = vFromDated; - SET vDateEnd = util.Dayend(vToDated); - - SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, - tp.quantity, - tp.ticketFk, - CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA' - AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0; - +BEGIN + + DECLARE vSijsnerClientFk INT DEFAULT 19752; + + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + + SET vDateStart = vFromDated; + SET vDateEnd = util.Dayend(vToDated); + + SELECT a.nickname shopName, + a.city , + IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, + tp.quantity, + tp.ticketFk, + CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA' + AND t.clientFk != vSijsnerClientFk + AND tp.quantity > 0; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53397,8 +53401,8 @@ DECLARE vTicketFk INT; DECLARE vSaleFk INT; DECLARE vClonTicket INT DEFAULT 0; -DECLARE cur1 CURSOR FOR -SELECT s.ticketFk, s.id +DECLARE cur1 CURSOR FOR +SELECT s.ticketFk, s.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk @@ -53414,17 +53418,17 @@ OPEN cur1; FETCH cur1 INTO vTicketFk, vSaleFk; WHILE done = 0 DO - + SELECT t.id INTO vClonTicket FROM vn.ticket t JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) WHERE t.warehouseFk = 44 LIMIT 1; - + SELECT vTicketFk, vClonTicket; - + IF vClonTicket = 0 THEN - + INSERT INTO ticket ( clientFk, shipped, @@ -53452,12 +53456,12 @@ FETCH cur1 INTO vTicketFk, vSaleFk; zonePrice, zoneBonus, routeFk - + FROM ticket WHERE id = vTicketFk; SET vClonTicket = LAST_INSERT_ID(); - + SELECT 'lstID', vClonTicket; /* INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) @@ -53467,20 +53471,20 @@ FETCH cur1 INTO vTicketFk, vSaleFk; WHERE t.id = vClonTicket; */ INSERT INTO ticketLog - SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); - + END IF; - + UPDATE vn.sale SET ticketFk = vClonTicket WHERE id = vSaleFk; SET vClonTicket = 0; - + SET done = 0; FETCH cur1 INTO vTicketFk, vSaleFk; - + END WHILE; CLOSE cur1; @@ -53505,8 +53509,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`() BEGIN - SELECT - e.expeditions_id as expeditionFk, + SELECT + e.expeditions_id as expeditionFk, date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, e.ticket_id as ticketFk, t.routeFk as routeFk @@ -53555,12 +53559,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getItemUbication`(vItemFk VARCHAR(22)) BEGIN - + /* * @deprecated Utilizar itemShelving_getInfo - * + * */ - + CALL itemshelving_getInfo(vItemFk); END ;; @@ -53609,7 +53613,7 @@ BEGIN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated FROM vn.greugeConfig; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk) SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk FROM vn.greuge @@ -53642,8 +53646,8 @@ DECLARE done BOOL DEFAULT FALSE; DECLARE vTicketFk INT; DECLARE rs CURSOR FOR - SELECT id FROM vn.ticket - WHERE shipped = util.yesterday() + SELECT id FROM vn.ticket + WHERE shipped = util.yesterday() AND clientFk = 400 AND warehouseFk IN (1,44); @@ -53654,13 +53658,13 @@ OPEN rs; FETCH rs INTO vTicketFk; WHILE NOT done DO - + INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk) - SELECT t.shipped, - s.itemFk, - s.quantity, + SELECT t.shipped, + s.itemFk, + s.quantity, b.buyingValue + b.freightValue + b.packageValue + b.comissionValue, - t.warehouseFk, + t.warehouseFk, w.id FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -53671,7 +53675,7 @@ WHILE NOT done DO AND s.quantity > 0; FETCH rs INTO vTicketFk; - + END WHILE; @@ -53829,7 +53833,7 @@ proc: BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWh - AND tr.landed BETWEEN vDateLastInventory + AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday AND NOT isRaid GROUP BY b.itemFk; @@ -53884,7 +53888,7 @@ proc: BEGIN inv.price3 = b.price3, inv.minPrice = b.minPrice, inv.producer = p.name; - + INSERT INTO buy( itemFk, quantity, buyingValue, @@ -53918,15 +53922,15 @@ proc: BEGIN FROM tmp.inventory; SELECT vWh, count(*), util.VN_NOW() FROM tmp.inventory; - + -- Actualizamos el campo lastUsed de vn.item UPDATE vn.item i JOIN tmp.inventory i2 ON i2.itemFk = i.id SET i.lastUsed = util.VN_NOW() WHERE i2.quantity; - + -- DROP TEMPORARY TABLE tmp.inventory; - + END LOOP; CLOSE cWarehouses; @@ -53940,11 +53944,11 @@ proc: BEGIN SELECT e.id as entryId, t.id as travelId FROM vn.travel t - JOIN vn.entry e ON e.travelFk = t.id + JOIN vn.entry e ON e.travelFk = t.id WHERE e.supplierFk = 4 AND t.shipped <= TIMESTAMPADD(DAY, -2, TIMESTAMPADD(DAY, -10, util.VN_CURDATE())) AND (DAY(t.shipped) <> 1 OR shipped < TIMESTAMPADD(MONTH, -12, util.VN_CURDATE())); - + DELETE e FROM vn.entry e JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; @@ -54006,7 +54010,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -54020,20 +54024,20 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + 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 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.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; - CREATE TEMPORARY TABLE tmp.lastEntryOk + CREATE TEMPORARY TABLE tmp.lastEntryOk (PRIMARY KEY (buyFk)) SELECT i.id AS itemFk, @@ -54043,7 +54047,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -54057,11 +54061,11 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + 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 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 @@ -54069,34 +54073,34 @@ BEGIN LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) ORDER BY tr.landed DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; - CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup (INDEX (warehouseFk,itemFk)) SELECT * FROM tmp.lastEntryOk tmp GROUP BY tmp.itemFk,tmp.warehouseFk; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.price2 = eo.price2 WHERE b.price2 = 0 ; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packing = eo.packing WHERE b.packing = 0; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; - + DROP TEMPORARY TABLE tmp.lastEntry; DROP TEMPORARY TABLE tmp.lastEntryOk; DROP TEMPORARY TABLE tmp.lastEntryOkGroup; @@ -54134,7 +54138,7 @@ BEGIN JOIN item i ON i.id = s.itemFk GROUP BY i.expenceFk HAVING amount != 0; - + INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) SELECT vInvoice, tst.expenceFk, @@ -54142,7 +54146,7 @@ BEGIN FROM ticketToInvoice t JOIN ticketService ts ON ts.ticketFk = t.id JOIN ticketServiceType tst ON tst.id = ts.ticketServiceTypeFk - HAVING amount != 0; + HAVING amount != 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54160,19 +54164,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT) -BEGIN +BEGIN DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()); - + SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate); - + DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - + CREATE TEMPORARY TABLE `ticketToInvoice` (PRIMARY KEY (`id`)) ENGINE = MEMORY SELECT Id_Ticket id FROM vn2008.Tickets WHERE (Fecha BETWEEN vMinDateTicket - AND vMaxTicketDate) AND Id_Consigna = vAddress + AND vMaxTicketDate) AND Id_Consigna = vAddress AND Factura IS NULL AND empresa_id = vCompany; END ;; @@ -54192,12 +54196,12 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromClient`( - IN vMaxTicketDate datetime, - IN vClientFk INT, + IN vMaxTicketDate datetime, + IN vClientFk INT, IN vCompanyFk INT) BEGIN DECLARE vMinTicketDate DATE; - + SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR); SET vMaxTicketDate = util.dayend(vMaxTicketDate); @@ -54227,10 +54231,10 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceFromTicket`(IN vTicket INT) -BEGIN +BEGIN DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - + CREATE TEMPORARY TABLE `ticketToInvoice` (PRIMARY KEY (`id`)) ENGINE = MEMORY @@ -54259,10 +54263,10 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS newInvoiceIn; CREATE TEMPORARY TABLE newInvoiceIn - SELECT + SELECT i.*, YEAR(i.booked) datedYear, - CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, + CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, (cc.id = c.id) isSameCountry, cit.id invoicesCount FROM invoiceIn i @@ -54275,7 +54279,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS newSupplier; CREATE TEMPORARY TABLE newSupplier - SELECT + SELECT s.*, REPLACE(s.account,' ','') supplierAccount, IF(c.CEE < 2, TRUE, FALSE) isUeeMember @@ -54288,11 +54292,11 @@ BEGIN CALL util.throw('INACTIVE_PROVIDER'); END IF; - SELECT IFNULL(MAX(i.serialNumber) + 1,1) + SELECT IFNULL(MAX(i.serialNumber) + 1,1) INTO vSerialNumber FROM invoiceIn i JOIN newInvoiceIn n - WHERE i.serial LIKE n.serial + WHERE i.serial LIKE n.serial AND YEAR(i.booked) = n.datedYear AND i.companyFk = n.companyFk GROUP BY i.companyFk; @@ -54321,7 +54325,7 @@ BEGIN CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); - SELECT SUM(iit.taxableBase * IF( i.serial= 'R' AND ti.Iva <> 'HP DEVENGADO 21 ISP', 1 +(ti.PorcentajeIva/100),1)), + SELECT SUM(iit.taxableBase * IF( i.serial= 'R' AND ti.Iva <> 'HP DEVENGADO 21 ISP', 1 +(ti.PorcentajeIva/100),1)), SUM(iit.foreignValue * IF( i.serial= 'R', 1 + (ti.PorcentajeIva/100),1)), iit.taxableBase/iit.foreignValue INTO vTotalAmount, vTotalAmountDivisa, vRate @@ -54344,7 +54348,7 @@ BEGIN CLAVE, empresa_id ) - SELECT + SELECT vBookNumber, n.bookEntried, s.supplierAccount, @@ -54355,7 +54359,7 @@ BEGIN n.invoicesCount, vInvoiceInId, n.companyFk - FROM newInvoiceIn n + FROM newInvoiceIn n JOIN newSupplier s; -- Línea de Gastos @@ -54365,7 +54369,7 @@ BEGIN CONTRA, EURODEBE, EUROHABER, - CONCEPTO, + CONCEPTO, CAMBIO, DEBEME, HABERME, @@ -54385,7 +54389,7 @@ BEGIN n.invoicesCount NFACTICK, n.companyFk empresa_id FROM newInvoiceIn n - JOIN newSupplier s + JOIN newSupplier s JOIN invoiceInTax iit ON iit.invoiceInFk = n.id JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = iit.expenceFk WHERE e.name != 'Suplidos Transitarios nacionales' @@ -54396,13 +54400,13 @@ BEGIN INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -54451,34 +54455,34 @@ BEGIN n.booked FECREGCON, n.companyFk FROM newInvoiceIn n - JOIN newSupplier s + JOIN newSupplier s JOIN invoiceInTax it ON n.id = it.invoiceInFk JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk JOIN invoiceInSerial iis ON iis.code = n.serial JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk LEFT JOIN ( - SELECT eWithheld.id - FROM invoiceInTax hold - JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld + SELECT eWithheld.id + FROM invoiceInTax hold + JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld WHERE hold.invoiceInFk = vInvoiceInId LIMIT 1 - ) eWithheld ON TRUE - WHERE it.taxTypeSageFk IS NOT NULL + ) eWithheld ON TRUE + WHERE it.taxTypeSageFk IS NOT NULL AND it.taxTypeSageFk NOT IN (22, 90) GROUP BY ti.PorcentajeIva, e.id; -- Línea iva inversor sujeto pasivo - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -54524,37 +54528,37 @@ BEGIN s.nif AS TERNIF, s.name AS TERNOM, n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s + FROM newInvoiceIn n + JOIN newSupplier s JOIN invoiceInTax it ON n.id = it.invoiceInFk JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk - JOIN invoiceInSerial iis ON iis.code = n.serial + JOIN invoiceInSerial iis ON iis.code = n.serial JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk WHERE ti.Iva = 'HP DEVENGADO 21 ISP' OR MID(s.account, 4, 1) = '1' GROUP BY ti.PorcentajeIva, e.id; - - -- Actualización del registro original + + -- Actualización del registro original UPDATE invoiceIn ii JOIN newInvoiceIn ni ON ii.id = ni.id SET ii.serialNumber = vSerialNumber, ii.isBooked = TRUE; - + -- Problemas derivados de la precisión en los decimales al calcular los impuestos - UPDATE XDiario - SET EURODEBE = EURODEBE - + UPDATE XDiario + SET EURODEBE = EURODEBE - (SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0) FROM( - SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference + SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference FROM XDiario WHERE ASIEN = vBookNumber )sub ) - WHERE ASIEN = vBookNumber + WHERE ASIEN = vBookNumber AND EURODEBE <> 0 ORDER BY id DESC LIMIT 1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54572,46 +54576,46 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT) -BEGIN - - IF !(SELECT COUNT(*) - FROM invoiceInDueDay iid - WHERE iid.invoiceInFk = vInvoiceInFk) THEN - - INSERT INTO invoiceInDueDay (invoiceInFk, - dueDated, - amount, - foreignValue) - SELECT vInvoiceInFk, - IF(payDay, - IF(vn.getNextDueDate(issued, detail, payDay) < DATE_ADD(created, INTERVAL 2 DAY), - DATE_ADD(created, INTERVAL 2 DAY), - vn.getNextDueDate(issued, detail, payDay)), - GREATEST(TIMESTAMPADD(DAY, 2, created), TIMESTAMPADD(DAY, detail, issued))), - IF((@cont:=@cont + 1) < cont, TRUNCATE(venc / cont, 2),venc-(TRUNCATE(venc / cont, 2) * (cont - 1))), - IF(@cont < cont, TRUNCATE(foreignValue / cont, 2), foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) - FROM ( SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detail)) venc, - SUM(iit.foreignValue)/COUNT(DISTINCT(pdd.detail)) foreignValue, - s.payDemFk, - ii.companyFk, - COUNT(DISTINCT(pdd.detail)) cont, - s.payDay, - ii.issued, - DATE(ii.created) created - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - LEFT JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk - JOIN supplier s ON s.id = ii.supplierFk - JOIN supplier s2 ON s2.id = ii.companyFk - JOIN vn.payDemDetail pdd ON pdd.id = s.payDemFk - WHERE ii.id = vInvoiceInFk - GROUP BY ii.id - ) sub - JOIN (SELECT @cont:=0) sub2 - JOIN vn.payDemDetail pdd ON pdd.id = sub.payDemFk - GROUP BY detail; - END IF; - +BEGIN + + IF !(SELECT COUNT(*) + FROM invoiceInDueDay iid + WHERE iid.invoiceInFk = vInvoiceInFk) THEN + + INSERT INTO invoiceInDueDay (invoiceInFk, + dueDated, + amount, + foreignValue) + SELECT vInvoiceInFk, + IF(payDay, + IF(vn.getNextDueDate(issued, detail, payDay) < DATE_ADD(created, INTERVAL 2 DAY), + DATE_ADD(created, INTERVAL 2 DAY), + vn.getNextDueDate(issued, detail, payDay)), + GREATEST(TIMESTAMPADD(DAY, 2, created), TIMESTAMPADD(DAY, detail, issued))), + IF((@cont:=@cont + 1) < cont, TRUNCATE(venc / cont, 2),venc-(TRUNCATE(venc / cont, 2) * (cont - 1))), + IF(@cont < cont, TRUNCATE(foreignValue / cont, 2), foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) + FROM ( SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100)*(s.countryFk = s2.countryFk)) * iit.taxableBase)/COUNT(DISTINCT(pdd.detail)) venc, + SUM(iit.foreignValue)/COUNT(DISTINCT(pdd.detail)) foreignValue, + s.payDemFk, + ii.companyFk, + COUNT(DISTINCT(pdd.detail)) cont, + s.payDay, + ii.issued, + DATE(ii.created) created + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposIva AS ti ON ti.CodigoIva= iit.taxTypeSageFk + JOIN supplier s ON s.id = ii.supplierFk + JOIN supplier s2 ON s2.id = ii.companyFk + JOIN vn.payDemDetail pdd ON pdd.id = s.payDemFk + WHERE ii.id = vInvoiceInFk + GROUP BY ii.id + ) sub + JOIN (SELECT @cont:=0) sub2 + JOIN vn.payDemDetail pdd ON pdd.id = sub.payDemFk + GROUP BY detail; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54633,9 +54637,9 @@ BEGIN DELETE FROM invoiceInDueDay WHERE invoiceInFk = vInvoiceInFk; - + CALL invoiceInDueDay_calculate(vInvoiceInFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54674,7 +54678,7 @@ BEGIN CALL vn2008.recibidaIvaInsert(vInvoiceInFk); CALL vn2008.recibidaVencimientoReplace(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -54719,7 +54723,7 @@ BEGIN CALL invoiceInTax_getFromEntries(vInvoiceInFk); CALL invoiceInDueDay_calculate(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -54751,7 +54755,7 @@ BEGIN SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr JOIN invoiceIn ii ON ii.id = vId - WHERE rr.dated <= ii.issued + WHERE rr.dated <= ii.issued AND rr.currencyFk = ii.currencyFk ; IF vDated THEN @@ -54760,13 +54764,13 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence - WHERE `name` = 'Adquisición mercancia Extracomunitaria' - GROUP BY id + SELECT id INTO vExpenceFk + FROM vn.expence + WHERE `name` = 'Adquisición mercancia Extracomunitaria' + GROUP BY id LIMIT 1; - - DELETE FROM invoiceInTax + + DELETE FROM invoiceInTax WHERE invoiceInFk = vId; INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) @@ -54780,9 +54784,9 @@ BEGIN JOIN entry e ON e.invoiceInFk = ii.id JOIN supplier s ON s.id = e.supplierFk JOIN buy b ON b.entryFk = e.id - LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk + LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk AND rr.dated = ii.issued - WHERE ii.id = vId + WHERE ii.id = vId HAVING taxableBase IS NOT NULL; END ;; DELIMITER ; @@ -54813,15 +54817,15 @@ BEGIN DECLARE vCountry INT; DECLARE vTaxArea VARCHAR(15); DECLARE vSpainCountryCode INT DEFAULT 1; - + SELECT id INTO vInvoiceFk - FROM invoiceOut + FROM invoiceOut WHERE ref = vInvoiceRef; - - UPDATE invoiceOut + + UPDATE invoiceOut SET hasPdf = 0 WHERE id = vInvoiceFk; - + SELECT s.countryFk INTO vCountry FROM supplier s JOIN invoiceOut io ON io.companyFk = s.id @@ -54830,30 +54834,30 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; CREATE TEMPORARY TABLE ticketToInvoice - SELECT id - FROM ticket + SELECT id + FROM ticket WHERE refFk = vInvoiceRef; CALL invoiceExpenceMake(vInvoiceFk); - + CALL invoiceTaxMake(vInvoiceFk,vTaxArea); - + UPDATE invoiceOut io JOIN ( SELECT SUM(amount) AS total - FROM invoiceOutExpence + FROM invoiceOutExpence WHERE invoiceOutFk = vInvoiceFk ) base JOIN ( SELECT SUM(vat) AS total - FROM invoiceOutTax + FROM invoiceOutTax WHERE invoiceOutFk = vInvoiceFk ) vat SET io.amount = base.total + vat.total WHERE io.id = vInvoiceFk; - + CALL vn.invoiceOutBooking(vInvoiceFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54898,7 +54902,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS rs; CREATE TEMPORARY TABLE rs - SELECT + SELECT c.accountingAccount AS clientBookingAccount, io.amount as totalAmount, CONCAT('n/fra ', io.ref) as simpleConcept, @@ -54932,19 +54936,19 @@ BEGIN WHERE io.id = vInvoice; CALL vn.ledger_next(vBookNumber); - + -- Linea del cliente INSERT INTO XDiario( ASIEN, FECHA, - SUBCTA, + SUBCTA, EURODEBE, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, rs.clientBookingAccount AS SUBCTA, @@ -54960,14 +54964,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, ioe.expenceFk AS SUBCTA, @@ -54981,8 +54985,8 @@ BEGIN JOIN invoiceOutExpence ioe WHERE ioe.invoiceOutFk = vInvoice; - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept FROM expence e JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id WHERE ioe.invoiceOutFk = vInvoice; @@ -54992,7 +54996,7 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, @@ -55020,7 +55024,7 @@ BEGIN TIPORECTIF, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, iot.pgcFk AS SUBCTA, @@ -55040,11 +55044,11 @@ BEGIN rs.FECHA_OP, rs.FECHA_EX, rs.TIPOOPE, - rs.NFACTICK, + rs.NFACTICK, rs.TERIDNIF, rs.TERNIF, rs.TERNOM, - pgc.mod340 AS L340, + pgc.mod340 AS L340, pgc.cplusTrascendency477Fk AS TIPOCLAVE, pgc.cplusTaxBreakFk as TIPOEXENCI, rs.TIPONOSUJE, @@ -55052,13 +55056,13 @@ BEGIN rs.TIPORECTIF, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutTax iot + JOIN invoiceOutTax iot JOIN pgc ON pgc.code = iot.pgcFk LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado - LEFT JOIN pgc pgce ON pgce.code = pe.equFk + LEFT JOIN pgc pgce ON pgce.code = pe.equFk LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. WHERE iot.invoiceOutFk = vInvoice; - + UPDATE invoiceOut SET booked = util.VN_CURDATE() WHERE id = vInvoice; @@ -55090,7 +55094,7 @@ BEGIN DECLARE done BOOL DEFAULT FALSE; - DECLARE rs CURSOR FOR + DECLARE rs CURSOR FOR SELECT io.id FROM invoiceOut io WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 @@ -55105,15 +55109,15 @@ BEGIN WHILE NOT done DO CALL invoiceOutBooking(vInvoice); - + FETCH rs INTO vInvoice ; - + SET vContador = vContador + 1; - + IF vContador MOD 50 = 0 THEN - + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - + END IF; END WHILE; @@ -55143,14 +55147,14 @@ BEGIN DECLARE vAsien INTEGER; DECLARE vSendMail BOOL; DECLARE vBody TEXT; - + SELECT ASIEN INTO vAsien - FROM XDiario + FROM XDiario WHERE SERIE = SUBSTRING(vRef, 1, 1) AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) LIMIT 1; - SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), + SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), CONCAT( ' @@ -55159,7 +55163,7 @@ BEGIN - ', + ', GROUP_CONCAT( CONCAT(' @@ -55172,14 +55176,14 @@ BEGIN ) SEPARATOR ' ' ), '
FECHACONCEPTO EURODEBE EUROHABER
', IFNULL(FECHA,''), '
' - ) + ) INTO vSendMail, vBody - FROM XDiario + FROM XDiario WHERE ASIEN = vAsien; - DELETE FROM XDiario + DELETE FROM XDiario WHERE ASIEN = vAsien; - + IF vSendMail THEN CALL mail_insert( 'administracion@verdnatura.es', @@ -55197,7 +55201,7 @@ BEGIN SET refFk = NULL WHERE refFk = vRef; - DELETE + DELETE FROM invoiceOut WHERE ref = vRef; @@ -55220,7 +55224,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE) BEGIN -SELECT +SELECT c.socialName as RazonSocial, c.fi as NIF, io.ref as Factura, @@ -55232,7 +55236,7 @@ SELECT pgc.rate as Tipo, iot.vat as Cuota, pgc.name as Concepto - + FROM vn.invoiceOut io JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id JOIN vn.client c ON c.id = io.clientFk @@ -55273,10 +55277,10 @@ BEGIN DECLARE done BOOL DEFAULT FALSE; - DECLARE rs CURSOR FOR + DECLARE rs CURSOR FOR SELECT id,ref FROM invoiceOut io - + WHERE issued >= '2017-07-01' AND companyFk = 1381 AND io.amount IS NULL @@ -55291,37 +55295,37 @@ BEGIN WHILE NOT done DO - SELECT s.countryFk + SELECT s.countryFk INTO vCountry FROM supplier s JOIN invoiceOut io ON io.companyFk = s.id WHERE io.id = vInvoice; - + SELECT IF(c.isEqualizated AND i.taxAreaFk = 'NATIONAL','EQU',i.taxAreaFk) INTO vTaxArea FROM invoiceOutSerial i - JOIN invoiceOut io ON io.serial = i.code + JOIN invoiceOut io ON io.serial = i.code JOIN client c ON c.id = io.clientFk WHERE io.id = vInvoice; - + DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; CREATE TEMPORARY TABLE ticketToInvoice - SELECT id - FROM ticket + SELECT id + FROM ticket WHERE refFk = vInvoiceRef; CALL invoiceExpenceMake(vInvoice); CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea); - + FETCH rs INTO vInvoice ,vInvoiceRef; - + SET vContador = vContador + 1; - + IF vContador MOD 50 = 0 THEN - + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - + END IF; END WHILE; @@ -55353,12 +55357,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_exportationFromClient`( BEGIN /** * Genera tabla temporal ticketToInvoice necesaría para el proceso de facturación - * Los abonos quedan excluidos en las exportaciones - * + * Los abonos quedan excluidos en las exportaciones + * * @param vMaxTicketDate Fecha hasta la cual cogera tickets para facturar * @param vClientFk Id del cliente a facturar * @param vCompanyFk Id de la empresa desde la que se factura - */ + */ DECLARE vMinTicketDate DATE; SET vMinTicketDate = util.firstDayOfYear(vMaxTicketDate - INTERVAL 1 YEAR); SET vMaxTicketDate = util.dayend(vMaxTicketDate); @@ -55367,7 +55371,7 @@ BEGIN CREATE TEMPORARY TABLE `ticketToInvoice` (PRIMARY KEY (`id`)) ENGINE = MEMORY - SELECT t.id + SELECT t.id FROM ticket t JOIN agencyMode am ON am.id = t.agencyModeFk WHERE t.clientFk = vClientFk @@ -55628,17 +55632,17 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromClient`( - IN vClientFk INT, - IN vSerial CHAR(2), + IN vClientFk INT, + IN vSerial CHAR(2), IN vMaxShipped DATE, - IN vCompanyFk INT, + IN vCompanyFk INT, IN vTaxArea VARCHAR(25), - IN vRef VARCHAR(25), + IN vRef VARCHAR(25), OUT vInvoiceId INT) BEGIN /** * Factura los tickets de un cliente hasta una fecha dada - * @param vClientFk Id del cliente a facturar + * @param vClientFk Id del cliente a facturar * @param vSerial Serie de factura * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar * @param vCompanyFk Id de la empresa desde la que se factura @@ -55657,11 +55661,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - END IF; + END IF; SELECT COUNT(*) INTO vIsExportation FROM vn.invoiceOutSerial - WHERE taxAreaFk = 'WORLD' + WHERE taxAreaFk = 'WORLD' AND `code` = vSerial; IF vIsExportation THEN @@ -55674,7 +55678,7 @@ BEGIN UPDATE invoiceOut SET `ref` = vRef - WHERE id = vInvoiceId + WHERE id = vInvoiceId AND vRef IS NOT NULL; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN @@ -55703,7 +55707,7 @@ BEGIN * Factura un ticket * @param vTicketFk Id del ticket * @param vSerial Serie de factura - * @param vTaxArea Area de la factura en caso de querer forzarlo, + * @param vTaxArea Area de la factura en caso de querer forzarlo, * en la mayoria de los casos poner NULL * @return vInvoiceId */ @@ -55718,11 +55722,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - - UPDATE invoiceOut + + UPDATE invoiceOut SET `ref` = vRef WHERE id = vInvoiceId; - END IF; + END IF; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN CALL invoiceOutBooking(vInvoiceId); @@ -55755,14 +55759,14 @@ BEGIN */ DELETE FROM invoiceOutTax WHERE invoiceOutFk = vInvoice; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; CREATE TEMPORARY TABLE tmp.ticket (KEY (ticketFk)) ENGINE = MEMORY SELECT id ticketFk FROM ticketToInvoice; - + CALL ticket_getTax(vTaxArea); INSERT INTO invoiceOutTax( @@ -55779,7 +55783,7 @@ BEGIN GROUP BY pgcFk HAVING BASE ORDER BY priority; - + DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticketAmount; @@ -55804,7 +55808,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemBarcode_update`(vItemFk INT,vCo BEGIN IF vDelete THEN DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode; -ELSE +ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); END IF; @@ -55826,8 +55830,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT) BEGIN - - SELECT cm3 Volumen_Entrada, + + SELECT cm3 Volumen_Entrada, cm3delivery Volumen_Salida, p.volume Volumen_del_embalaje, p.width Ancho_del_embalaje, @@ -55840,11 +55844,11 @@ BEGIN b.id buyFk, b.entryFk, w.name warehouseFk - FROM vn.itemCost ic - JOIN vn.item i ON i.id = ic.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk WHERE ic.itemFk = vItemFk AND ic.warehouseFk = vWarehouseFk; @@ -55868,33 +55872,33 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture I BEGIN /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro - * + * * @param vDaysInFuture Rango de dias para calcular entradas y salidas - * + * */ - + DECLARE vWarehouseFk INT; SELECT s.warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.code = 'FUENTES_PICASSE'; - + CALL cache.stock_refresh(FALSE); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, i.size, i.subName, - v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, - fue.Fuentes, + v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, + fue.Fuentes, alb.Albenfruit, - sale.venta, - IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) + sale.venta, + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, + IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes FROM vn.itemShelving ish @@ -55902,7 +55906,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'FUENTES_PICASSE' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) fue ON fue.itemFk = i.id LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit @@ -55911,7 +55915,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'ALBENFRUIT' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) alb ON alb.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( @@ -55936,9 +55940,9 @@ BEGIN AND warehouse_id = vWarehouseFk GROUP BY item_id ) mov ON mov.item_id = i.id - WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) + WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) AND i.itemPackingTypeFk = 'H' - AND ic.shortLife + AND ic.shortLife ; END ;; @@ -55960,7 +55964,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementFromTicket`(vTicket INT) BEGIN /** - * Llama a itemPlacementUpdateVisible + * Llama a itemPlacementUpdateVisible * de los articulos de la tabla temporal tmp.itemPlacement(itemFk) * @treturn tmp.itemPlacement * @param vTicket Id del Ticket @@ -55974,9 +55978,9 @@ BEGIN FROM ticket t JOIN sale s ON s.ticketFk = t.id WHERE t.id = vTicket; - + CALL itemPlacementUpdateVisible(); - + DROP TEMPORARY TABLE tmp.itemPlacement; END ;; DELIMITER ; @@ -56009,7 +56013,7 @@ BEGIN CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), ' x ', ish.packing, - IF ( + IF ( LEAST(ish.stock,quantity) MOD ish.packing, CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), '' @@ -56040,7 +56044,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT) BEGIN - UPDATE vn.itemPlacementSupply + UPDATE vn.itemPlacementSupply SET priority = 10 WHERE id = vId; @@ -56066,7 +56070,7 @@ BEGIN DECLARE vId INT; DECLARE vLastParkingFk INT; DECLARE vNextParkingFk INT; - + SELECT sh.parkingFk INTO vLastParkingFk FROM vn.itemShelvingPlacementSupply isps JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk @@ -56074,9 +56078,9 @@ BEGIN WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; - + SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); - + SELECT ipsl.id INTO vId FROM vn.itemPlacementSupplyList ipsl JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk @@ -56085,13 +56089,13 @@ BEGIN AND ipsl.sectorFk = vSector ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created LIMIT 1; - + UPDATE vn.itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; - - SELECT * FROM vn.itemPlacementSupplyList - WHERE id = vId + + SELECT * FROM vn.itemPlacementSupplyList + WHERE id = vId AND sectorFk = vSector; END ;; @@ -56166,20 +56170,20 @@ BEGIN * @param vItemFk item id * @param vTicketFk ticket id * @param vShowType mostrar tipos - */ + */ DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; - - + + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -56189,16 +56193,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -56231,7 +56235,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1 COLLATE utf8_general_ci) DESC, (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, @@ -56239,7 +56243,7 @@ BEGIN (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + END ;; DELIMITER ; @@ -56265,7 +56269,7 @@ BEGIN * @param vSaleFk id de la tabla sale * @param vMateFk articulo sustituto * @ param vQuantity cantidad que se va a sustituir - */ + */ DECLARE vTicketFk INT; DECLARE vItemFk INT; DECLARE vWarehouseFk SMALLINT; @@ -56274,41 +56278,41 @@ BEGIN DECLARE vBox INT; DECLARE vPacking INT; DECLARE vRoundQuantity INT DEFAULT 1; - + SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk WHERE s.id = vSaleFk; - + UPDATE vn.sale SET quantity = quantity - vQuantity WHERE id = vSaleFk; - + CALL vn.buyUltimate(vWarehouseFk, vDate); - + SELECT `grouping`, groupingMode, packing INTO vGrouping,vBox,vPacking FROM buy b JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk; - + IF vBox = 2 AND vPacking > 0 THEN SET vRoundQuantity = vPacking; END IF; IF vBox = 1 AND vGrouping > 0 THEN SET vRoundQuantity = vGrouping; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept) SELECT vTicketFk, vMateFk, CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName) FROM vn.item i WHERE id = vMateFk; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + CALL vn.sale_calculateComponent(vSaleFk, NULL); - + INSERT INTO vn.itemProposal(itemFk, mateFk, counter) VALUES(vItemFk, vMateFk, 1) ON DUPLICATE KEY UPDATE counter = counter + 1; @@ -56337,13 +56341,13 @@ BEGIN DECLARE vCalcFk INT; DECLARE vTypeFk INT; DECLARE vResultsMax INT DEFAULT 10; - + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -56353,16 +56357,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i + FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -56380,7 +56384,7 @@ BEGIN (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, a.available, IFNULL(ip.counter,0) counter - FROM vn.item i + FROM vn.item i JOIN cache.available a ON a.item_id = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 @@ -56394,7 +56398,7 @@ BEGIN (it1.value = vValue1 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, @@ -56430,7 +56434,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.item SELECT vItem id; - + CALL item_refreshTags(); DROP TEMPORARY TABLE tmp.item; @@ -56453,24 +56457,24 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT) BEGIN - + DECLARE vStarted DATE; DECLARE vEnded DATETIME; SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded - FROM `time` t + FROM `time` t WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period; SELECT t.shipped, w.name warehouse, - s.ticketFk, + s.ticketFk, c.quality, t.nickname client, - am.name agencyName, + am.name agencyName, wk.code salesPerson, s.itemFk, - IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, - s.quantity, + IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, + s.quantity, s.price, s.priceFixed, s.discount, @@ -56480,15 +56484,15 @@ BEGIN wk.id salesPersonFk FROM sale s JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id - LEFT JOIN saleBuy sb ON sb.saleFk = s.id - LEFT JOIN buy b ON b.id = sb.buyFk - LEFT JOIN item ig ON ig.id = b.itemOriginalFk + LEFT JOIN saleBuy sb ON sb.saleFk = s.id + LEFT JOIN buy b ON b.id = sb.buyFk + LEFT JOIN item ig ON ig.id = b.itemOriginalFk WHERE s.itemFk = vItemFk AND t.shipped BETWEEN vStarted AND vEnded AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk) @@ -56515,9 +56519,9 @@ BEGIN DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE vn.item SET minimum = min WHERE id = vItemFk; - + END ;; @@ -56539,8 +56543,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3)) BEGIN SELECT p.`column` AS col , p.`row` - FROM vn.shelving s - JOIN parking p ON s.parkingFk = p.id + FROM vn.shelving s + JOIN parking p ON s.parkingFk = p.id WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci; END ;; DELIMITER ; @@ -56581,36 +56585,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) BEGIN - + /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro - * + * @param vShelvingFk Matrícula del carro + * */ - - SELECT isl.itemShelvingFk, - isl.created, - isl.accion, - isl.itemFk, - isl.shelvingFk, - isl.quantity, + + SELECT isl.itemShelvingFk, + isl.created, + isl.accion, + isl.itemFk, + isl.shelvingFk, + isl.quantity, isl.visible, - isl.available, - isl.grouping, - isl.packing, - isl.stars, - item.longName, - item.size, - item.subName, - worker.code, + isl.available, + isl.grouping, + isl.packing, + isl.stars, + item.longName, + item.size, + item.subName, + worker.code, isl.accion - FROM item - JOIN itemShelvingLog isl ON item.id = isl.itemFk + FROM item + JOIN itemShelvingLog isl ON item.id = isl.itemFk JOIN worker ON isl.workerFk = worker.id WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk ORDER BY isl.created DESC; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56629,7 +56633,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) BEGIN - + DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; @@ -56648,9 +56652,9 @@ BEGIN END IF; - IF (SELECT COUNT(*) FROM vn.itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE vn.itemShelving @@ -56680,8 +56684,8 @@ BEGIN LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id WHERE i.id = vItemFk; - END IF; - + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56702,9 +56706,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMatch`(vEntryFk INT, vA BEGIN DECLARE vTravelFk INT; - - SELECT travelFk INTO vTravelFk - FROM entry + + SELECT travelFk INTO vTravelFk + FROM entry WHERE id = vEntryFk; SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed @@ -56717,7 +56721,7 @@ BEGIN GROUP BY itemFk ) b ON b.itemFk = i.id LEFT JOIN ( - SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas + SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas FROM itemShelving ish JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking pk ON pk.id = sh.parkingFk @@ -56757,7 +56761,7 @@ BEGIN UPDATE vn.itemShelving SET visible = visible - vQuantity WHERE id = vItemShelvingFk; - + END ;; DELIMITER ; @@ -56780,47 +56784,47 @@ BEGIN DECLARE vVisibleCache INT; DECLARE vWarehouseFk INT; - + SELECT warehouseFk INTO vWarehouseFk FROM vn.sector WHERE id = vSectorFk; CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk); - - SELECT t.id as ticketFk, - CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, - s.itemFk, - s.concept, - v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, + + SELECT t.id as ticketFk, + CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, + s.itemFk, + s.concept, + v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, i.subName, - GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, + GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, s.id as saleFk, IFNULL(sub3.transit,0) transit, v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento - FROM vn.ticket t + FROM vn.ticket t JOIN vn.ticketState tst ON tst.ticketFk = t.id JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26 - JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id + JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id LEFT JOIN - (SELECT itemFk, sum(saldo) as transit - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + (SELECT itemFk, sum(saldo) as transit + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 AND sectorFk = vSectorFk GROUP BY itemFk) sub3 ON sub3.itemFk = i.id - WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity + WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity AND IFNULL(sub3.transit,0) < s.quantity - AND s.isPicked = FALSE + AND s.isPicked = FALSE AND s.reserved = FALSE - AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) + AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) AND tst.isPreviousPreparable = TRUE AND t.warehouseFk = vWarehouseFk AND iss.sectorFk = vSectorFk AND mm.Id_Movimiento IS NULL ORDER BY itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56839,7 +56843,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(vSectorFk INT) proc:BEGIN - + DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE hasFatherSector BOOLEAN; @@ -56847,25 +56851,25 @@ proc:BEGIN DECLARE vWarehouseFk INT DEFAULT 0; DECLARE vSonSectorFk INT; DECLARE vWorkerFk INT; - - SELECT s.workerFk - INTO vWorkerFk + + SELECT s.workerFk + INTO vWorkerFk FROM vn.sector s WHERE s.id = vSectorFk; - + IF IFNULL(vWorkerFk,0) THEN - + CALL vn.itemShelvingRadar_Urgent(vWorkerFk); LEAVE proc; - + end if; - - + + SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk - FROM vn.worker w + FROM vn.worker w JOIN vn.sector s ON s.code = w.code WHERE s.id = vSectorFk; - + SELECT s.id INTO vSectorFk FROM vn.sector s WHERE s.warehouseFk = vWarehouseFk @@ -56875,21 +56879,21 @@ proc:BEGIN SELECT COUNT(*) INTO hasFatherSector FROM vn.sector WHERE sonFk = vSectorFk; - + SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk FROM vn.sector WHERE id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + IF hasFatherSector THEN - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM ( SELECT iss.itemFk, i.longName, @@ -56900,7 +56904,7 @@ proc:BEGIN SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible,0)) as visible, vSectorFk as sectorFk - + FROM vn.itemShelvingStock iss JOIN vn.sector s ON s.id = iss.sectorFk JOIN vn.item i on i.id = iss.itemFk @@ -56909,11 +56913,11 @@ proc:BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE vSectorFk IN (iss.sectorFk, s.sonFk) AND it.workerFk != 3366 - + GROUP BY iss.itemFk - + UNION ALL - + SELECT v.item_id, i.longName, i.size, @@ -56923,7 +56927,7 @@ proc:BEGIN 0 downstairs, IF(it.isPackaging, NULL, v.visible) visible, vSectorFk as sectorFk - FROM cache.visible v + FROM cache.visible v JOIN vn.item i on i.id = v.item_id JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk @@ -56932,8 +56936,8 @@ proc:BEGIN AND iss.itemFk IS NULL AND it.isInventory ) sub GROUP BY itemFk; - - SELECT ishr.*, + + SELECT ishr.*, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente FROM tmp.itemShelvingRadar ishr @@ -56948,13 +56952,13 @@ proc:BEGIN ) sub ON sub.itemFk = ishr.itemFk ORDER BY i.typeFk, i.longName ; - - + + ELSE - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT iss.itemFk, 0 `hour`, 0 `minute`, @@ -56966,7 +56970,7 @@ proc:BEGIN IFNULL(a.available,0) available, IFNULL(v.visible - iss.visible,0) dayEndVisible, IFNULL(v.visible - iss.visible,0) firstNegative, - IFNULL(v.visible - iss.visible,0) itemPlacementVisible, + IFNULL(v.visible - iss.visible,0) itemPlacementVisible, IFNULL(i.minimum * b.packing,0) itemPlacementSize, ips.onTheWay, iss.visible itemShelvingStock, @@ -56980,13 +56984,13 @@ proc:BEGIN LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 GROUP BY itemFk ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - OR iss.sectorFk = vSectorFk; - /* + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + OR iss.sectorFk = vSectorFk; + /* UPDATE tmp.itemShelvingRadar isr JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk SET isr.dayEndVisible = isr.dayEndVisible + iss.visible, @@ -56997,10 +57001,10 @@ proc:BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; CREATE TEMPORARY TABLE tmp.itemOutTime SELECT *,SUM(amount) quantity - FROM + FROM (SELECT item_id itemFk, - amount, - IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes FROM vn2008.item_out io JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id @@ -57008,23 +57012,23 @@ proc:BEGIN JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk JOIN vn.state s ON s.id = ts.stateFk LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - WHERE st.created > util.VN_CURDATE() + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + WHERE st.created > util.VN_CURDATE() AND st.isChecked ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk WHERE t.warehouseFk = vWarehouseFk - AND s.isPicked = 0 - AND NOT io.Reservado + AND s.isPicked = 0 + AND NOT io.Reservado AND stPrevious.saleFk IS NULL - AND io.dat >= util.VN_CURDATE() + AND io.dat >= util.VN_CURDATE() AND io.dat < util.VN_CURDATE()+1 ) sub GROUP BY itemFk, hours, minutes; - + INSERT INTO tmp.itemShelvingRadar (itemFk) SELECT itemFk FROM tmp.itemOutTime - ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); @@ -57034,13 +57038,13 @@ proc:BEGIN dayEndVisible = 0, firstNegative = 0 WHERE itemPlacementVisible = - itemShelvingStock; - */ + */ SELECT * FROM tmp.itemShelvingRadar; END IF; DROP TEMPORARY TABLE tmp.itemShelvingRadar; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57064,24 +57068,24 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, i.minimum, CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho, CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible, @@ -57101,11 +57105,11 @@ BEGIN AND IFNULL(tst.productionOrder,0) < 5 GROUP BY s.itemFK ) ts ON ts.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57129,34 +57133,34 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving FROM vn.item i JOIN tmp.item ti ON ti.itemFk = i.id LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57183,7 +57187,7 @@ BEGIN CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - SELECT * FROM + SELECT * FROM (SELECT sub.itemFk, sub.longName, CONCAT(DATE_FORMAT(sub2.etd,'%H:%i'), ' salen ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -57201,14 +57205,14 @@ BEGIN 0 upstairs, SUM(IFNULL(iss.visible,0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible,0)) visible, - IFNULL(iss.sectorFk,0) sectorFk + IFNULL(iss.sectorFk,0) sectorFk FROM itemShelvingStock iss JOIN sector s ON s.id = iss.sectorFk JOIN item i on i.id = iss.itemFk JOIN itemType it ON it.id = i.typeFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = @vCalcVisibleFk WHERE s.warehouseFk = vWarehouseFk - GROUP BY itemFk + GROUP BY itemFk ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente, MIN(zc.`hour`) etd FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id @@ -57220,8 +57224,8 @@ BEGIN AND ISNULL(st.saleFk) AND ct.code IN ('normal', 'trust') GROUP BY s.itemFk - ) sub2 ON sub2.itemFk = sub.itemFk - UNION ALL + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL SELECT v.item_id , i.longName, CONCAT(DATE_FORMAT(sub5.etd,'%H:%i'), ' salen ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -57235,7 +57239,7 @@ BEGIN FROM cache.visible v JOIN item i ON i.id = v.item_id JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id + LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id LEFT JOIN (SELECT s.itemFk , SUM(s.quantity) pendiente, MIN(zc.`hour`) etd FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id @@ -57249,7 +57253,7 @@ BEGIN GROUP BY s.itemFk ) sub5 ON sub5.itemFk = v.item_id WHERE v.calc_id = @vCalcVisibleFk - AND ISNULL(iss.itemFk) + AND ISNULL(iss.itemFk) ) sub3 WHERE nicho ORDER BY LEFT(producer,3), etd, producer; @@ -57273,10 +57277,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_Add`(vItemShelving BEGIN /** * Añade línea a itemShelvingSale y regulariza el carro - * + * * @param vItemShelvingFk Id itemShelving * @param vSaleFk Id de sale - * @param vQuantity cantidad a regularizar + * @param vQuantity cantidad a regularizar */ INSERT INTO itemShelvingSale(itemShelvingFk, saleFk, @@ -57371,7 +57375,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN - + /** * Añade registro o lo actualiza si ya existe. @@ -57383,7 +57387,7 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra * @param vPacking el packing del producto, NULL para coger el de la ultima compra * @param vWarehouseFk indica el sector - * + * **/ DECLARE vItemFk INT; @@ -57393,21 +57397,21 @@ BEGIN IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); - INSERT INTO shelving(code, parkingFk) + INSERT INTO shelving(code, parkingFk) SELECT vShelvingFk, id - FROM parking + FROM parking WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; END IF; - IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE itemShelving SET visible = visible+vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; ELSE CALL cache.last_buy_refresh(FALSE); @@ -57492,7 +57496,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_BuyerGet`( ) BEGIN SELECT * FROM vn.buyer; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57519,15 +57523,15 @@ proc:BEGIN * @return Lista de articulos */ DECLARE vCalcVisibleFk INT; - + IF vBuyerFk = 103 THEN -- hay que arreglarlo despues de la campaña PAK 23/04/2022 - CALL vn.itemShelvingRadar_Urgent(); + CALL vn.itemShelvingRadar_Urgent(); LEAVE proc; END IF; CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - SELECT * FROM + SELECT * FROM (SELECT sub.itemFk, sub.longName, CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -57544,7 +57548,7 @@ proc:BEGIN 0 upstairs, SUM(IFNULL(iss.visible,0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible,0)) visible, - IFNULL(iss.sectorFk,0) sectorFk + IFNULL(iss.sectorFk,0) sectorFk FROM itemShelvingStock iss JOIN sector s ON s.id = iss.sectorFk JOIN item i on i.id = iss.itemFk @@ -57552,19 +57556,19 @@ proc:BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE s.warehouseFk = vWarehouseFk AND it.workerFk = vBuyerFk - GROUP BY itemFk + GROUP BY itemFk ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND ISNULL(st.saleFk) AND ct.code IN ('normal', 'trust') GROUP BY s.itemFk - ) sub2 ON sub2.itemFk = sub.itemFk - UNION ALL + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL SELECT v.item_id , i.longName, CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -57577,11 +57581,11 @@ proc:BEGIN FROM cache.visible v JOIN item i ON i.id = v.item_id JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id + LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id LEFT JOIN (SELECT s.itemFk , SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -57590,7 +57594,7 @@ proc:BEGIN GROUP BY s.itemFk ) sub5 ON sub5.itemFk = v.item_id WHERE v.calc_id = vCalcVisibleFk - AND ISNULL(iss.itemFk) + AND ISNULL(iss.itemFk) AND it.workerFk = vBuyerFk ) sub3 WHERE nicho @@ -57614,14 +57618,14 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_get`(IN vShelvingFk VARCHAR(8)) BEGIN /** - * Lista artículos de itemshelving + * Lista artículos de itemshelving * * @param vShelvingFk matrícula del carro - * + * **/ - SELECT ish.itemFk as item, - IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) as description, + SELECT ish.itemFk as item, + IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) as description, ish.visible as visible, ceil(ish.visible/ish.packing) as stickers, ish.packing as packing, @@ -57654,24 +57658,24 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getAlternatives`(vShelvingFk VARCHAR(10)) -BEGIN -/** - * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula - * del carro que se le ha pasado. - * - * @param vShelvingFk matricula del carro - */ - SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder - FROM itemShelving is2 - JOIN shelving sh ON sh.code = is2.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - LEFT JOIN worker w ON w.sectorFk = s.id AND w.id = account.myUser_getId() - JOIN warehouse wh ON wh.id = s.warehouseFk - JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci - GROUP BY is2.id - ORDER BY p.pickingOrder DESC; +BEGIN +/** + * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula + * del carro que se le ha pasado. + * + * @param vShelvingFk matricula del carro + */ + SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder + FROM itemShelving is2 + JOIN shelving sh ON sh.code = is2.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + LEFT JOIN worker w ON w.sectorFk = s.id AND w.id = account.myUser_getId() + JOIN warehouse wh ON wh.id = s.warehouseFk + JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci + GROUP BY is2.id + ORDER BY p.pickingOrder DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57727,35 +57731,35 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) BEGIN - + /* Devuelve la minima fecha en que se necesita cada producto en esa matricula. - * + * * @param vShelvingFk Matrícula del carro o pallet */ - + DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk FROM shelving s - JOIN parking p ON s.parkingFk = p.id + JOIN parking p ON s.parkingFk = p.id JOIN sector st ON st.id = p.sectorFk WHERE s.code = vShelvingFk COLLATE utf8_unicode_ci; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingDistinct; CREATE TEMPORARY TABLE tmp.itemShelvingDistinct (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, SUM(visible) visible - FROM vn.itemShelving + FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - + GROUP BY itemFk; + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT * FROM tmp.itemShelvingDistinct; - + DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay; CREATE TEMPORARY TABLE tmp.stockByDay (index (itemFk, dated)) @@ -57766,16 +57770,16 @@ BEGIN FROM ( SELECT * FROM ( SELECT t2.* FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock WHERE warehouse_id = vWarehouseFk UNION ALL SELECT ish.itemFk, - sum(visible), util.VN_CURDATE() - FROM vn.itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id + FROM vn.itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve + WHERE s.isReserve GROUP BY ish.itemFk UNION ALL SELECT item_id, sum(iei.amount), dat @@ -57784,9 +57788,9 @@ BEGIN AND warehouse_id = vWarehouseFk AND isVirtualStock = FALSE GROUP BY item_id, dat - UNION ALL + UNION ALL SELECT item_id, sum(ieo.amount), dat - FROM vn2008.item_entry_out ieo + FROM vn2008.item_entry_out ieo WHERE dat >= util.VN_CURDATE() AND warehouse_id = vWarehouseFk GROUP BY item_id, dat @@ -57797,11 +57801,11 @@ BEGIN WHERE io.dat >= util.VN_CURDATE() AND io.warehouse_id = vWarehouseFk GROUP BY io.item_id, io.dat - ) t2 + ) t2 JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t order by t.itemFk, DATE(t.dated), t.amount DESC) t3; - - SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock + + SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock FROM tmp.stockByDay sbd JOIN vn.item i ON i.id = sbd.itemFk JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk @@ -57829,46 +57833,46 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_inventory`(vParkingFromFk INT, vParkingToFk INT) -BEGIN - - /** - * Devuelve un listado de ubicaciones a revisar - * - * @param vParkingFromFk Parking de partida, identificador de vn.parking - * @param vParkingToFk Parking de llegada, identificador de vn.parking - */ - - DECLARE vSectorFk INT; - DECLARE vPickingOrderFrom INT; - DECLARE vPickingOrderTo INT; - - SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom - FROM vn.parking p - WHERE p.id = vParkingFromFk; - - SELECT p.pickingOrder INTO vPickingOrderTo - FROM vn.parking p - WHERE p.id = vParkingToFk; - - CALL vn.visible_getMisfit(vSectorFk); - - SELECT p.code parking , - ish.shelvingFk , - ish.itemFk, - i.longName, - ish.visible , - ish.visible / ish.packing packs, - ish.packing, - sm.visible - sm.parked faltan - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo - AND p.sectorFk = vSectorFk - ORDER BY p.pickingOrder ; - +BEGIN + + /** + * Devuelve un listado de ubicaciones a revisar + * + * @param vParkingFromFk Parking de partida, identificador de vn.parking + * @param vParkingToFk Parking de llegada, identificador de vn.parking + */ + + DECLARE vSectorFk INT; + DECLARE vPickingOrderFrom INT; + DECLARE vPickingOrderTo INT; + + SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom + FROM vn.parking p + WHERE p.id = vParkingFromFk; + + SELECT p.pickingOrder INTO vPickingOrderTo + FROM vn.parking p + WHERE p.id = vParkingToFk; + + CALL vn.visible_getMisfit(vSectorFk); + + SELECT p.code parking , + ish.shelvingFk , + ish.itemFk, + i.longName, + ish.visible , + ish.visible / ish.packing packs, + ish.packing, + sm.visible - sm.parked faltan + FROM vn.itemShelving ish + JOIN vn.item i ON i.id = ish.itemFk + JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo + AND p.sectorFk = vSectorFk + ORDER BY p.pickingOrder ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57896,9 +57900,9 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving */ UPDATE itemShelving - SET visible = vVisible, - packing = vPacking, - grouping = vGrouping + SET visible = vVisible, + packing = vPacking, + grouping = vGrouping WHERE id = vShelf; END ;; @@ -57925,34 +57929,34 @@ BEGIN * @param vDated max date to filter * @param vItemFk item id **/ - + DECLARE vIsLogifloraDay BOOLEAN; SET vDated = TIMESTAMP(DATE(vDated), '00:00:00'); SELECT vn.isLogifloraDay(vDated, vWarehouseFk) INTO vIsLogifloraDay ; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemList; CREATE TEMPORARY TABLE tmp.itemList (UNIQUE INDEX i USING HASH (itemFk)) ENGINE = MEMORY SELECT itemFk, SUM(quantity) stock, SUM(quantity) visible, SUM(quantity) available FROM ( - SELECT itemFk, quantity + SELECT itemFk, quantity FROM itemTicketOut WHERE shipped >= util.VN_CURDATE() AND shipped < vDated AND warehouseFk = vWarehouseFk AND (vItemFk IS NULL OR itemFk = vItemFk) UNION ALL - SELECT itemFk, quantity + SELECT itemFk, quantity FROM itemEntryIn i - LEFT JOIN edi.warehouseFloramondo wf ON wf.entryFk = i.entryFk + LEFT JOIN edi.warehouseFloramondo wf ON wf.entryFk = i.entryFk WHERE i.landed >= util.VN_CURDATE() AND i.landed < vDated AND i.warehouseInFk = vWarehouseFk AND (vItemFk IS NULL OR i.itemFk = vItemFk) AND (ISNULL(wf.entryFk) OR vIsLogifloraDay) UNION ALL - SELECT itemFk, quantity + SELECT itemFk, quantity FROM itemEntryOut WHERE shipped >= util.VN_CURDATE() AND shipped < vDated AND warehouseOutFk = vWarehouseFk @@ -57963,7 +57967,7 @@ BEGIN CALL `cache`.stock_refresh (FALSE); INSERT INTO tmp.itemList (itemFk,stock,visible,available) - SELECT item_id,amount,amount,amount + SELECT item_id,amount,amount,amount FROM `cache`.stock WHERE warehouse_id = vWarehouseFk AND (vItemFk IS NULL OR vItemFk = item_id) ON DUPLICATE KEY UPDATE @@ -57989,7 +57993,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagMake`(vItemFk INT) BEGIN -/* * Crea los tags usando la tabla plantilla itemTag +/* * Crea los tags usando la tabla plantilla itemTag * y si no existe a partir de la ficha del artículo. * @param vItemFk El item al que se le añaden los tags */ @@ -57999,33 +58003,33 @@ BEGIN DECLARE vProducer VARCHAR(50); DECLARE vOrigin VARCHAR(20); DECLARE vTypeFk INTEGER; - - DELETE FROM itemTag + + DELETE FROM itemTag WHERE itemFk = vItemFk; - - SELECT typeFk INTO vTypeFk + + SELECT typeFk INTO vTypeFk FROM item WHERE id = vItemFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT vItemFk, itt.tagFk, NULL, itt.priority FROM itemTag it LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk WHERE it.itemFk = vItemFk; - + IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN - SELECT ik.name, i.size, i.category, p.name, o.name + SELECT ik.name, i.size, i.category, p.name, o.name INTO vInk, vSize, vCategory, vProducer, vOrigin FROM item i LEFT JOIN ink ik ON ik.id = i.inkFk LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible LEFT JOIN origin o ON o.id = i.originFk WHERE i.id = vItemFk; - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 1, vInk, 1); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES (vItemFk, 8, vSize, 2); @@ -58034,11 +58038,11 @@ BEGIN INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 37, vProducer, 4); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 35, vOrigin, 5); END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58059,12 +58063,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT) BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.typeFk = itemTypeFk; UPDATE itemTag it @@ -58073,8 +58077,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -58099,12 +58103,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorderByName`(vName VARCHAR BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.`name` LIKE CONCAT(vName,'%'); UPDATE itemTag it @@ -58113,8 +58117,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -58136,37 +58140,37 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100)) -BEGIN - - /* Reemplaza los tags de un artículo por los de otro, así como su imagen - * - * @param vItemFromFk id de vn.item con el artículo del que se toman los tags - * @param vItemToFk id de vn.item con el artículo del que se toman los tags - * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk - */ - - DELETE FROM vn.itemTag - WHERE itemFk = vItemToFk; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemToFk, tagFk, value, priority - FROM vn.itemTag - WHERE itemFk = vItemFromFk; - - IF ISNULL(vPicture) THEN - - SELECT image INTO vPicture - FROM vn.item - WHERE id = vItemFromFk; - - END IF; - - UPDATE vn.item i - SET i.image = vPicture - WHERE i.id = vItemToFk; - - CALL vn.itemRefreshTags(vItemToFk); - +BEGIN + + /* Reemplaza los tags de un artículo por los de otro, así como su imagen + * + * @param vItemFromFk id de vn.item con el artículo del que se toman los tags + * @param vItemToFk id de vn.item con el artículo del que se toman los tags + * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk + */ + + DELETE FROM vn.itemTag + WHERE itemFk = vItemToFk; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT vItemToFk, tagFk, value, priority + FROM vn.itemTag + WHERE itemFk = vItemFromFk; + + IF ISNULL(vPicture) THEN + + SELECT image INTO vPicture + FROM vn.item + WHERE id = vItemFromFk; + + END IF; + + UPDATE vn.item i + SET i.image = vPicture + WHERE i.id = vItemToFk; + + CALL vn.itemRefreshTags(vItemToFk); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58191,9 +58195,9 @@ BEGIN SELECT DISTINCT id FROM vn.itemCategory WHERE merchandise <> FALSE; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -58204,45 +58208,45 @@ BEGIN INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, util.VN_CURDATE()) AND util.VN_CURDATE() GROUP BY s.itemFk; - + DROP TABLE IF EXISTS tmp.topSeller; - CREATE TEMPORARY TABLE tmp.topSeller - ( + CREATE TEMPORARY TABLE tmp.topSeller + ( `id` int(11) NOT NULL DEFAULT '0', `typeFk` smallint(5) unsigned NOT NULL, `itemCategoryFk` int(10) unsigned NOT NULL, `total` bigint(21) NOT NULL DEFAULT '0' ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - + OPEN rs; read_loop: LOOP FETCH rs INTO vCategoryFk; - + IF vDone THEN LEAVE read_loop; END IF; - + INSERT INTO tmp.topSeller SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total FROM tmp.topSellerMin tsm INNER JOIN vn.itemType it ON it.id = tsm.typeFk WHERE it.categoryFk = vCategoryFk ORDER BY tsm.itemFk ,tsm.total DESC - LIMIT 5; + LIMIT 5; END LOOP; CLOSE rs; - + SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk, ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total FROM tmp.topSeller ts INNER JOIN vn.item i ON i.id = ts.id INNER JOIN vn.itemType it ON it.id = ts.typeFk INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk; - + DROP TABLE IF EXISTS topSellerMin; DROP TABLE IF EXISTS tmp.topSeller; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58259,62 +58263,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTrash`( - vItemFk INT, - vWarehouseFk INT, - vQuantity INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTrash`( + vItemFk INT, + vWarehouseFk INT, + vQuantity INT, vIsTrash BOOLEAN) -BEGIN - - DECLARE vTicketFk INT; - DECLARE vClientFk INT; - DECLARE vCompanyVnlFk INT DEFAULT 442; - DECLARE vCalc INT; - - SELECT barcodeToItem(vItemFk) INTO vItemFk; - - SELECT IF(vIsTrash, 200, 400) INTO vClientFk; - - SELECT t.id INTO vTicketFk - FROM ticket t - JOIN address a ON a.id=t.addressFk - WHERE t.warehouseFk = vWarehouseFk - AND t.clientFk = vClientFk - AND DATE(t.shipped) = util.VN_CURDATE() - AND a.isDefaultAddress - LIMIT 1; - - CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); - - IF vTicketFk IS NULL THEN - - CALL ticket_add( - vClientFk, - util.VN_CURDATE(), - vWarehouseFk, - vCompanyVnlFk, - NULL, - NULL, - NULL, - util.VN_CURDATE(), - account.myUser_getId(), - FALSE, - vTicketFk); - END IF; - - INSERT INTO sale(ticketFk, itemFk, concept, quantity) - SELECT vTicketFk, - vItemFk, - CONCAT(longName,' ',getWorkerCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)), - vQuantity - FROM item - WHERE id = vItemFk; - - UPDATE cache.visible - SET visible = visible - vQuantity - WHERE calc_id = vCalc - AND item_id = vItemFk; - +BEGIN + + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT DEFAULT 442; + DECLARE vCalc INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT IF(vIsTrash, 200, 400) INTO vClientFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id=t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = util.VN_CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + IF vTicketFk IS NULL THEN + + CALL ticket_add( + vClientFk, + util.VN_CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + NULL, + NULL, + NULL, + util.VN_CURDATE(), + account.myUser_getId(), + FALSE, + vTicketFk); + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity) + SELECT vTicketFk, + vItemFk, + CONCAT(longName,' ',getWorkerCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)), + vQuantity + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = visible - vQuantity + WHERE calc_id = vCalc + AND item_id = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58355,7 +58359,7 @@ SET tag6 = t.name, value6 = it.value WHERE it.priority = 2 AND (vItem IS NULL OR vItem = it.itemFk); -UPDATE item i +UPDATE item i JOIN itemTag it ON it.itemFk = i.id JOIN tag t ON t.id = it.tagFk SET tag7 = t.name, value7 = it.value @@ -58455,7 +58459,7 @@ BEGIN ORDER BY i.id; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET vDone = TRUE; - + SELECT itemFrom INTO vItemFrom FROM vn.itemCleanLog ORDER BY created DESC @@ -58477,9 +58481,9 @@ BEGIN OPEN curItemClean; curItemClean: LOOP - + FETCH curItemClean INTO vItemOld, vItemNew; - + START TRANSACTION; # Deletes @@ -58507,7 +58511,7 @@ BEGIN DELETE FROM vn.itemProposal WHERE itemFk = vItemOld; - + SET @isTriggerDisabled := TRUE; DELETE FROM vn.itemTag WHERE itemFk = vItemOld; @@ -58573,19 +58577,19 @@ BEGIN WHERE id = vItemOld; COMMIT; - + SELECT isStop INTO vIsStop FROM vn.itemCleanConfig; IF vIsStop OR vItemOld > vItemEnd OR vDone THEN LEAVE curItemClean; END IF; - + SET vCounter = vCounter + 1; END LOOP; CLOSE curItemClean; - + INSERT INTO itemCleanLog (itemFrom, itemDeleted) VALUES (vItemOld, vCounter); @@ -58733,7 +58737,7 @@ BEGIN `in` AS invalue, `out`, @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, - @currentLineFk := IF (@shipped < util.VN_CURDATE() + @currentLineFk := IF (@shipped < util.VN_CURDATE() OR (@shipped = util.VN_CURDATE() AND (isPicked OR alertLevel >= 2)), lineFk,@currentLineFk) lastPreparedLineFk, isTicket, @@ -58761,7 +58765,7 @@ BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.id = + JOIN alertLevel al ON al.id = CASE WHEN tr.landed < util.VN_CURDATE() THEN 3 WHEN tr.landed = util.VN_CURDATE() AND tr.isReceived = TRUE THEN 3 @@ -58769,7 +58773,7 @@ BEGIN END JOIN state st ON st.code = al.code WHERE tr.landed >= vDateInventory - AND vWarehouse = tr.warehouseInFk + AND vWarehouse = tr.warehouseInFk AND b.itemFk = vItemId AND e.isExcludedFromAvailable = FALSE AND e.isRaid = FALSE @@ -58795,7 +58799,7 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk JOIN warehouse w ON w.id = tr.warehouseOutFk JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.id = + JOIN alertLevel al ON al.id = CASE WHEN tr.shipped < util.VN_CURDATE() THEN 3 WHEN tr.shipped = util.VN_CURDATE() AND tr.isReceived = TRUE THEN 3 @@ -58832,7 +58836,7 @@ BEGIN LEFT JOIN state st ON st.code = ts.code JOIN client c ON c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk - JOIN alertLevel al ON al.id = + JOIN alertLevel al ON al.id = CASE WHEN t.shipped < util.VN_CURDATE() THEN 3 WHEN t.shipped > util.dayEnd(util.VN_CURDATE()) THEN 0 @@ -58840,7 +58844,7 @@ BEGIN END LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id - LEFT JOIN claimBeginning cb ON s.id = cb.saleFk + LEFT JOIN claimBeginning cb ON s.id = cb.saleFk WHERE t.shipped >= vDateInventory AND s.itemFk = vItemId AND vWarehouse =t.warehouseFk @@ -58952,7 +58956,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getLack`(IN vForce BOOLEAN, IN BEGIN /** * Calcula una tabla con el máximo negativo visible para cada producto y almacen - * + * * @param vForce Fuerza el recalculo del stock * @param vDays Numero de dias a considerar **/ @@ -58961,31 +58965,31 @@ BEGIN CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL); CALL item_getMinETD(); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, w.id warehouseFk, - p.`name` producer, + p.`name` producer, i.`size`, i.category, - w.name warehouse, + w.name warehouse, SUM(IFNULL(sub.amount,0)) lack, i.inkFk, - IFNULL(im.timed, util.midnight()) timed - FROM (SELECT item_id, - warehouse_id, + IFNULL(im.timed, util.midnight()) timed + FROM (SELECT item_id, + warehouse_id, amount FROM cache.stock WHERE amount > 0 UNION ALL - SELECT itemFk, - warehouseFk, + SELECT itemFk, + warehouseFk, amount FROM tmp.itemMinacum ) sub JOIN warehouse w ON w.id = sub.warehouse_id JOIN item i ON i.id = sub.item_id - LEFT JOIN producer p ON p.id = i.producerFk - JOIN itemType it ON it.id = i.typeFk + LEFT JOIN producer p ON p.id = i.producerFk + JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id WHERE w.isForTicket @@ -59106,12 +59110,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinETD`() BEGIN - + /* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy. - * + * * @return tmp.itemMinETD(itemFk, timed) */ - + DECLARE vMidnight DATETIME DEFAULT util.midnight(); DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD; @@ -59122,7 +59126,7 @@ BEGIN SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed FROM ticket t JOIN sale s ON s.ticketFk = t.id - LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN `zone` z ON z.id = t.zoneFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight GROUP BY s.itemFk; END ;; @@ -59152,33 +59156,33 @@ BEGIN * @param vWarehouseFk warehouse id * @param vDate fecha para revisar disponible * @param vIsShowedByType para mostrar solo artículos de ese tipo - */ + */ DECLARE vCalcFk INT; DECLARE vTypeFk INT; - + DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag7 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag8 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + DECLARE vValue1 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue5 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue6 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59211,7 +59215,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1) DESC, (it1.value = vValue1) DESC, - (i.tag6 = vTag6) DESC, + (i.tag6 = vTag6) DESC, (i.value6 = vValue6) DESC, (i.tag5 = vTag5) DESC, (i.value5 = vValue5) DESC, @@ -59220,7 +59224,7 @@ BEGIN (i.tag8 = vTag8) DESC, (i.value8 = vValue8) DESC LIMIT 30; - + END ;; DELIMITER ; @@ -59241,18 +59245,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_GetVisible`(vWarehouse SMALLINT, vItem INT) BEGIN DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, util.VN_CURDATE()); - + INSERT INTO vn2008.tmp_item (item_id, visible) SELECT item_id, SUM(amount) amount FROM ( - SELECT i.itemFk AS item_id, quantity AS amount + SELECT i.itemFk AS item_id, quantity AS amount FROM itemTicketOut i - LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk + LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk JOIN state s ON s.id = ts.stateFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM saleTracking st + LEFT JOIN (SELECT DISTINCT saleFk + FROM saleTracking st JOIN state s ON s.id = st.stateFk - WHERE st.created > util.VN_CURDATE() + WHERE st.created > util.VN_CURDATE() AND (s.isPicked OR st.isChecked) ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk WHERE i.warehouseFk = vWarehouse @@ -59260,7 +59264,7 @@ BEGIN AND (s.isPicked OR i.reserved OR stPrevious.saleFk ) AND i.shipped >= util.VN_CURDATE() AND i.shipped < vTomorrow UNION ALL - SELECT iei.itemFk, quantity + SELECT iei.itemFk, quantity FROM itemEntryIn iei WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > util.VN_CURDATE()*/) AND iei.landed >= util.VN_CURDATE() AND iei.landed < vTomorrow @@ -59268,7 +59272,7 @@ BEGIN AND (vItem IS NULL OR iei.itemFk = vItem) AND iei.isVirtualStock is FALSE UNION ALL - SELECT itemFk, quantity + SELECT itemFk, quantity FROM itemEntryOut WHERE isDelivered != FALSE AND shipped >= util.VN_CURDATE() AND shipped < vTomorrow @@ -59301,7 +59305,7 @@ BEGIN * * @param temporary table tmp.item(id) del articulo **/ - + DECLARE done INT DEFAULT FALSE; DECLARE vItemFk INT; DECLARE cur1 CURSOR FOR SELECT id FROM tmp.item; @@ -59311,13 +59315,13 @@ BEGIN OPEN cur1; read_loop: LOOP - + FETCH cur1 INTO vItemFk; - + IF done THEN LEAVE read_loop; END IF; - + UPDATE item i LEFT JOIN itemTag it1 ON it1.priority = 1 AND it1.itemFk = i.id LEFT JOIN itemTag it2 ON it2.priority = 2 AND it2.itemFk = i.id @@ -59332,54 +59336,54 @@ BEGIN LEFT JOIN tagAbbreviation ta2 ON ta2.`value` = it2.`value` AND ta2.tagFk IS NULL LEFT JOIN itemTag it3 ON it3.priority = 3 AND it3.itemFk = i.id LEFT JOIN tagAbbreviation ta3 ON ta3.`value` = it3.`value` - SET i.`name` = CONCAT_WS(' ', - IFNULL(ta1.abbreviation,it1.`value`), - IFNULL(ta2.abbreviation,it2.`value`), + SET i.`name` = CONCAT_WS(' ', + IFNULL(ta1.abbreviation,it1.`value`), + IFNULL(ta2.abbreviation,it2.`value`), IF(i.isFloramondo,'',IFNULL(ta3.abbreviation,it3.`value`))) WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 4 SET i.subName = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 5 LEFT JOIN tag t ON t.id = it.tagFk SET tag5 = t.name, value5 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 6 LEFT JOIN tag t ON t.id = it.tagFk SET tag6 = t.name, value6 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 7 - LEFT JOIN tag t ON t.id = it.tagFk + LEFT JOIN tag t ON t.id = it.tagFk SET i.tag7 = t.name, i.value7 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 8 LEFT JOIN tag t ON t.id = it.tagFk SET tag8 = t.name, value8 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 9 LEFT JOIN tag t ON t.id = it.tagFk SET tag9 = t.name, value9 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 10 LEFT JOIN tag t ON t.id = it.tagFk SET tag10 = t.name, value10 = it.`value` WHERE i.id = vItemFk; - -- Al insertar el tag color se modifica también el antiguo campo color + -- Al insertar el tag color se modifica también el antiguo campo color UPDATE item i JOIN tag t ON t.overwrite = 'inkFk' JOIN itemTag it ON it.itemFk = i.id AND it.tagFk = t.id @@ -59394,7 +59398,7 @@ BEGIN JOIN origin o ON o.`name` = it.`value` SET i.originFk = o.id WHERE i.id = vItemFk; - + -- Al insertar el tag medida se modifica también en la tabla item UPDATE item i JOIN tag t ON t.overwrite = 'size' @@ -59409,28 +59413,28 @@ BEGIN JOIN producer p ON p.`name` = it.`value` SET i.producerFk = p.id WHERE i.id = vItemFk; - + -- Al insertar el tag tallos se modifica también en la tabla item UPDATE item i JOIN tag t ON t.overwrite = 'stems' JOIN itemTag it ON it.itemFk = i.id AND it.tagFk = t.id SET i.stems = it.`value` WHERE i.id = vItemFk; - + -- Al insertar el tag categoria se modifica también en la tabla item UPDATE item i JOIN tag t ON t.overwrite = 'category' JOIN itemTag it ON it.itemFk = i.id AND it.tagFk = t.id SET i.category = it.`value` WHERE i.id = vItemFk; - + -- Comprueba si existe un genérico y lo asigna CALL vn.item_setGeneric(vItemFk); - + END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59454,7 +59458,7 @@ BEGIN * * @param temporary table tmp.item(id) del articulo **/ - + DECLARE done INT DEFAULT FALSE; DECLARE vItemFk INT; DECLARE cur1 CURSOR FOR SELECT id FROM tmp.item; @@ -59464,13 +59468,13 @@ BEGIN OPEN cur1; read_loop: LOOP - + FETCH cur1 INTO vItemFk; - + IF done THEN LEAVE read_loop; END IF; - + UPDATE item i LEFT JOIN itemTag it1 ON it1.priority = 1 AND it1.itemFk = i.id LEFT JOIN itemTag it2 ON it2.priority = 2 AND it2.itemFk = i.id @@ -59485,54 +59489,54 @@ BEGIN LEFT JOIN tagAbbreviation ta2 ON ta2.`value` = it2.`value` LEFT JOIN itemTag it3 ON it3.priority = 3 AND it3.itemFk = i.id LEFT JOIN tagAbbreviation ta3 ON ta3.`value` = it3.`value` - SET i.`name` = CONCAT_WS(' ', - IFNULL(ta1.abbreviation,it1.`value`), - IFNULL(ta2.abbreviation,it2.`value`), + SET i.`name` = CONCAT_WS(' ', + IFNULL(ta1.abbreviation,it1.`value`), + IFNULL(ta2.abbreviation,it2.`value`), IF(i.isFloramondo,'',IFNULL(ta3.abbreviation,it3.`value`))) WHERE i.id = vItemFk; - + UPDATE item i JOIN tmp.itemToRefresh tmpI ON tmpI.id = i.id LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 4 SET i.subName = it.`value`; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 5 LEFT JOIN tag t ON t.id = it.tagFk SET tag5 = t.name, value5 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 6 LEFT JOIN tag t ON t.id = it.tagFk SET tag6 = t.name, value6 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 7 - LEFT JOIN tag t ON t.id = it.tagFk + LEFT JOIN tag t ON t.id = it.tagFk SET i.tag7 = t.name, i.value7 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 8 LEFT JOIN tag t ON t.id = it.tagFk SET tag8 = t.name, value8 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 9 LEFT JOIN tag t ON t.id = it.tagFk SET tag9 = t.name, value9 = it.`value` WHERE i.id = vItemFk; - + UPDATE item i LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 10 LEFT JOIN tag t ON t.id = it.tagFk SET tag10 = t.name, value10 = it.`value` WHERE i.id = vItemFk; - -- Al insertar el tag color se modifica también el antiguo campo color + -- Al insertar el tag color se modifica también el antiguo campo color UPDATE item i JOIN tag t ON t.overwrite = 'inkFk' JOIN itemTag it ON it.itemFk = i.id AND it.tagFk = t.id @@ -59547,7 +59551,7 @@ BEGIN JOIN origin o ON o.`name` = it.`value` SET i.originFk = o.id WHERE i.id = vItemFk; - + -- Al insertar el tag medida se modifica también en la tabla item UPDATE item i JOIN tag t ON t.overwrite = 'size' @@ -59562,18 +59566,18 @@ BEGIN JOIN producer p ON p.`name` = it.`value` SET i.producerFk = p.id WHERE i.id = vItemFk; - + -- Al insertar el tag tallos se modifica también en la tabla item UPDATE item i JOIN tag t ON t.overwrite = 'stems' JOIN itemTag it ON it.itemFk = i.id AND it.tagFk = t.id SET i.stems = it.`value` WHERE i.id = vItemFk; - + END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59591,21 +59595,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_saveReference`(vBarcode VARCHAR(22), vReference VARCHAR(150)) -BEGIN - -/** - * Actualiza la referencia del item - * - * @param vBarcode del item - * @param vReference referencia a actualizar - */ - - DECLARE vItemFk INT; - - SELECT barcodeToItem(vBarcode) INTO vItemFk; - - UPDATE item SET comment = vReference WHERE id = vItemFk; - +BEGIN + +/** + * Actualiza la referencia del item + * + * @param vBarcode del item + * @param vReference referencia a actualizar + */ + + DECLARE vItemFk INT; + + SELECT barcodeToItem(vBarcode) INTO vItemFk; + + UPDATE item SET comment = vReference WHERE id = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59623,47 +59627,47 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT) -BEGIN -/** - * Asigna el código genérico a un item, salvo que sea un código de item genérico. - * - * @param vSelf identificador de vn.item - */ - DECLARE vGenericFk INT; - - SELECT itemFk INTO vGenericFk - FROM ( - SELECT itemFk, (sum(matches) = maxMatches) `match` - FROM ( - SELECT ga.id gaid, - ga.itemFk, - (it.value <=> ga.origin) - + (it.value <=> ga.color) - + (it.value <=> ga.quality) - + (it.value <=> ga.numFlores) - + (it.value <=> ga.category) - + (it.value <=> ga.productor) matches, - !ISNULL(ga.origin) - +!ISNULL(ga.color) - +!ISNULL(ga.quality) - +!ISNULL(ga.numFlores) - +!ISNULL(ga.category) - +!ISNULL(ga.productor) maxMatches - FROM vn.item i - JOIN vn.itemTag it ON it.itemFk = i.id - JOIN vn.genericAllocation ga - ON (i.typeFk = ga.typeFk OR ga.typeFk IS NULL) - AND (i.longName = ga.longName OR ga.longName IS NULL) - AND (i.`size` = ga.`size` OR ga.`size` IS NULL) - AND i.id != ga.itemFk - WHERE i.id = vSelf - AND NOT i.isFloramondo) sub - GROUP BY gaid - HAVING `match`) sub2; - - UPDATE vn.item - SET genericFk = vGenericFk - WHERE id = vSelf; +BEGIN +/** + * Asigna el código genérico a un item, salvo que sea un código de item genérico. + * + * @param vSelf identificador de vn.item + */ + DECLARE vGenericFk INT; + + SELECT itemFk INTO vGenericFk + FROM ( + SELECT itemFk, (sum(matches) = maxMatches) `match` + FROM ( + SELECT ga.id gaid, + ga.itemFk, + (it.value <=> ga.origin) + + (it.value <=> ga.color) + + (it.value <=> ga.quality) + + (it.value <=> ga.numFlores) + + (it.value <=> ga.category) + + (it.value <=> ga.productor) matches, + !ISNULL(ga.origin) + +!ISNULL(ga.color) + +!ISNULL(ga.quality) + +!ISNULL(ga.numFlores) + +!ISNULL(ga.category) + +!ISNULL(ga.productor) maxMatches + FROM vn.item i + JOIN vn.itemTag it ON it.itemFk = i.id + JOIN vn.genericAllocation ga + ON (i.typeFk = ga.typeFk OR ga.typeFk IS NULL) + AND (i.longName = ga.longName OR ga.longName IS NULL) + AND (i.`size` = ga.`size` OR ga.`size` IS NULL) + AND i.id != ga.itemFk + WHERE i.id = vSelf + AND NOT i.isFloramondo) sub + GROUP BY gaid + HAVING `match`) sub2; + + UPDATE vn.item + SET genericFk = vGenericFk + WHERE id = vSelf; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59681,19 +59685,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT) -BEGIN - +BEGIN + /** - * Actualiza el valor de item.packingShelve - * - * @param vSelf Identificador de vn.item - * @param vPacking Cantidad de unidades de venta que caben en una bandeja - */ - - UPDATE vn.item i - SET i.packingShelve = vPacking - WHERE i.id = vSelf; - + * Actualiza el valor de item.packingShelve + * + * @param vSelf Identificador de vn.item + * @param vPacking Cantidad de unidades de venta que caben en una bandeja + */ + + UPDATE vn.item i + SET i.packingShelve = vPacking + WHERE i.id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59711,15 +59715,15 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingType`(vItem INT, vItemPackingTypeFk VARCHAR(1)) -BEGIN -/** - * Update the packing type of an item - * - * @param vItem id del item a actualizar - * @param vItemPackingTypeFk packing type - */ - UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; - +BEGIN +/** + * Update the packing type of an item + * + * @param vItem id del item a actualizar + * @param vItemPackingTypeFk packing type + */ + UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59743,9 +59747,9 @@ BEGIN DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; DECLARE vInventoried2 DATE; DECLARE vDateDayEnd DATETIME; - + SET vDateDayEnd = util.dayEnd(vDated); - + SELECT landed INTO vInventoried FROM travel tr JOIN entry E ON E.travelFk = tr.id @@ -59755,7 +59759,7 @@ BEGIN LIMIT 1; SET vHasNotInventory = IF (vInventoried is null, TRUE, FALSE); - + IF vHasNotInventory THEN SELECT landed INTO vInventoried2 @@ -59776,13 +59780,13 @@ BEGIN CREATE TEMPORARY TABLE inv (warehouseFk SMALLINT, Id_Article BIGINT, - cantidad INT, + cantidad INT, coste DOUBLE DEFAULT 0, total DOUBLE DEFAULT 0, Almacen VARCHAR(20), PRIMARY KEY (Almacen, Id_Article) USING HASH) ENGINE = MEMORY; - + IF vHasNotInventory = TRUE THEN INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -59859,7 +59863,7 @@ BEGIN AND it.isInventory ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,0,1); - END IF; + END IF; -- Mercancia en transito INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -59877,7 +59881,7 @@ BEGIN AND t.isInventory AND e.isConfirmed ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity); - + CALL vn.buyUltimate(NULL,vDateDayEnd); UPDATE inv i @@ -59892,20 +59896,20 @@ BEGIN IF vIsDetailed THEN SELECT inv.warehouseFk, - i.id itemFk, - i.longName , - i.size, - inv.Cantidad, + i.id itemFk, + i.longName , + i.size, + inv.Cantidad, tp.name Tipo, - ic.name Reino, - inv.coste, + ic.name Reino, + inv.coste, cast(inv.total as decimal(10,2)) total, almacen FROM inv JOIN warehouse w on w.id = warehouseFk JOIN item i ON i.id = inv.Id_Article JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN itemCategory ic ON ic.id = tp.categoryFk WHERE w.valuatedInventory and inv.total > 0 order by inv.total desc; @@ -59952,37 +59956,37 @@ BEGIN * @param vConcept descripcion * @param vAmount cantidad que se compensa * @param vCompany empresa - * @param vOriginalAccount cuenta contable desde la cual se compensa - * - */ + * @param vOriginalAccount cuenta contable desde la cual se compensa + * + */ DECLARE vNewBookEntry INT; DECLARE vIsClientCompensation INT; DECLARE vClientFk INT; DECLARE vSupplierFk INT; DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - + CALL ledger_next(vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci; - SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation - FROM client + SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation + FROM client WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci; - + SET @vAmount1:= 0.0; SET @vAmount2:= 0.0; - INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) - VALUES ( vNewBookEntry, - vDated, - vOriginalAccount, - vCompensationAccount, - vConcept, + INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) + VALUES ( vNewBookEntry, + vDated, + vOriginalAccount, + vCompensationAccount, + vConcept, @vAmount1:= IF( - (vIsOriginalAClient AND vAmount > 0) OR - (NOT vIsOriginalAClient AND vAmount < 0), - 0, + (vIsOriginalAClient AND vAmount > 0) OR + (NOT vIsOriginalAClient AND vAmount < 0), + 0, ABS(vAmount) ), @vAmount2:= IF(@vAmount1, @@ -59991,20 +59995,20 @@ BEGIN ), vCompanyFk ), - ( vNewBookEntry, - vDated, - vCompensationAccount, - vOriginalAccount, - vConcept, + ( vNewBookEntry, + vDated, + vCompensationAccount, + vOriginalAccount, + vConcept, @vAmount2, @vAmount1, vCompanyFk); - + IF vIsClientCompensation THEN IF vIsOriginalAClient THEN SET vAmount = -vAmount; END IF; - INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) + INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE); ELSE IF NOT vIsOriginalAClient THEN @@ -60012,7 +60016,7 @@ BEGIN END IF; SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation'; - + INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated) VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE); END IF; @@ -60034,10 +60038,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`(OUT vNewBookEntry INT) BEGIN - + UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1); SET vNewBookEntry = LAST_INSERT_ID(); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60064,7 +60068,7 @@ BEGIN * @param vEntity Nombre que hace referencia a la tabla. * @param descripcion Descripción de la acción realizada por el usuario */ - + CALL logAddWithUser(vOriginFk, account.myUser_getId(), vActionCode, vEntity, vDescription); END ;; DELIMITER ; @@ -60132,15 +60136,15 @@ BEGIN * @param vEntity Nombre que hace referencia a la tabla. */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vEntity, 'Log'); - + SET @qryLog := CONCAT( 'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot', ' INNER JOIN account.user u ON u.id = ot.userFk', ' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; END ;; @@ -60165,9 +60169,9 @@ BEGIN SET @buildingOrder := 0; SET @route := 0; set @cajas := 0; - + UPDATE tmp.sorter - SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 + SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 where date(created) = vDate order by routeFk, created, weight DESC; @@ -60185,23 +60189,23 @@ set @cajas := 0; UPDATE tmp.sorter SET lungGrow = IF(palletOrder = 0, -13, lungGrow); - + DELETE FROM tmp.lungSize WHERE dia = vDate; - + INSERT INTO tmp.lungSize(dia, hora,size) select vDate,hora, @cajas := @cajas + cajas as size from ( select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0 - from tmp.sorter + from tmp.sorter where date(created) = vDate group by hora ) sub; - + SELECT * FROM tmp.lungSize WHERE dia = vDate; - - + + END ;; @@ -60222,23 +60226,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas * @param vPlate número de matrícula - * @param vWorkerFk id del worker - * -*/ - UPDATE vn.machineWorker mw - JOIN vn.machine m ON m.id = mw.machineFk + * @param vWorkerFk id del worker + * +*/ + UPDATE vn.machineWorker mw + JOIN vn.machine m ON m.id = mw.machineFk SET mw.outTimed = util.VN_NOW() WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate) AND ISNULL(mw.outTimed); - + INSERT INTO machineWorker (machineFk, workerFk) SELECT m.id, vWorkerFk FROM machine m - WHERE m.plate= vPlate; + WHERE m.plate= vPlate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60258,21 +60262,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT) BEGIN /** - * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, + * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, * si es jefe de producción muestra el historial completo. - * + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk); - SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed + SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed FROM machineWorker mw JOIN machine m ON m.plate = vPlate WHERE mw.machineFk = m.id AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk) - ORDER BY mw.inTimed DESC; + ORDER BY mw.inTimed DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60291,13 +60295,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** - * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, - * + * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vMachineFk INT(10); @@ -60306,24 +60310,24 @@ BEGIN SELECT m.id INTO vMachineFk FROM machine m WHERE m.plate = vPlate; - + SELECT maxHours INTO vMaxHours FROM machineWorkerConfig; - IF (SELECT COUNT(*) + IF (SELECT COUNT(*) FROM machineWorker m WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN - + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN + UPDATE machineWorker m SET m.outTimed = CURRENT_TIMESTAMP() - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed) AND m.machineFk = vMachineFk; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60341,22 +60345,22 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machine_getWorkerPlate`(vWorkerFk INT) -BEGIN -/** - * Selecciona la matrícula del vehículo del workerfk - * - * @param vWorkerFk el id del trabajador - * - * - **/ - - SELECT m.plate - FROM machine m - JOIN machineWorker mw ON mw.machineFk = m.id - WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,util.VN_NOW()) - AND ISNULL(mw.outTimed) - AND mw.workerFk = vWorkerFk; - +BEGIN +/** + * Selecciona la matrícula del vehículo del workerfk + * + * @param vWorkerFk el id del trabajador + * + * + **/ + + SELECT m.plate + FROM machine m + JOIN machineWorker mw ON mw.machineFk = m.id + WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,util.VN_NOW()) + AND ISNULL(mw.outTimed) + AND mw.workerFk = vWorkerFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60382,12 +60386,12 @@ BEGIN /** * Inserta en la tabla vn.mail * - * @param vReceiver Receptor del correo + * @param vReceiver Receptor del correo * @param vReplyTo A quién contestar el correo * @param vSubject Título del correo * @param vBody Cuerpo del correo */ - + DECLARE vIsRepeated BOOLEAN; SELECT COUNT(*) INTO vIsRepeated @@ -60428,12 +60432,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `makeNewItem`() BEGIN DECLARE newItemFk INT; - + SELECT getNewItemId() INTO newItemFk; - + INSERT INTO item(id,name,typeFk,originFk) SELECT newItemFk, 'Nuevo artículo', 78,39; - + SELECT newItemFk; @@ -60461,34 +60465,34 @@ BEGIN DECLARE vMinute INT DEFAULT 0; DECLARE vBoxes INT; - + DROP TEMPORARY TABLE IF EXISTS vn.pcsDay; CREATE TEMPORARY TABLE vn.pcsDay SELECT 0 as hh, 0 as mm, 0 as boxes; - + -- Creamos una tabla soporte para acumular las cajas a lo largo del dia WHILE vHour < 24 DO - + WHILE vMinute < 59 DO - + SET vMinute = vMinute + 1; - + INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute); - + END WHILE; - + SET vMinute = -1; SET vHour = vHour + 1; - + END WHILE; - + -- Acumulamos UPDATE vn.pcsDay pd LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm) SET pd.boxes = pd.boxes + pg.box; - + SELECT * FROM vn.pcsDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60511,7 +60515,7 @@ BEGIN * Recalcula el mana consumido por un trabajador * * @param vWorkerFk Id Trabajador - */ + */ DECLARE vWorkerIsExcluded BOOLEAN; DECLARE vFromDated DATE; DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,util.VN_CURDATE()); @@ -60520,32 +60524,32 @@ BEGIN DECLARE vClaimMana INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT COUNT(*) INTO vWorkerIsExcluded FROM workerManaExcluded WHERE workerFk = vWorkerFk; - + IF NOT vWorkerIsExcluded THEN - SELECT id INTO vMana + SELECT id INTO vMana FROM `component` WHERE code = 'mana'; - - SELECT id INTO vAutoMana + + SELECT id INTO vAutoMana FROM `component` WHERE code = 'autoMana'; - - SELECT id INTO vClaimMana + + SELECT id INTO vClaimMana FROM `component` WHERE code = 'manaClaim'; - - SELECT id INTO vManaBank + + SELECT id INTO vManaBank FROM `bank` WHERE code = 'mana'; - - SELECT id INTO vManaGreugeType + + SELECT id INTO vManaGreugeType FROM `greugeType` WHERE code = 'mana'; - SELECT max(dated) INTO vFromDated + SELECT max(dated) INTO vFromDated FROM clientManaCache; - + REPLACE workerMana (workerFk, amount) - SELECT vWorkerFk, sum(mana) FROM + SELECT vWorkerFk, sum(mana) FROM ( SELECT s.quantity * sc.value as mana FROM ticket t @@ -60566,8 +60570,8 @@ BEGIN FROM greuge g JOIN client c ON c.id = g.clientFk WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() - UNION ALL + AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() + UNION ALL SELECT cc.mana FROM clientManaCache cc JOIN client c ON c.id = cc.clientFk @@ -60594,20 +60598,20 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlConnectionsSorter_kill`() BEGIN /** - * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre - */ - + * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre + */ + DECLARE vDone INT DEFAULT 0; DECLARE vProcesId INT; DECLARE vCursor CURSOR FOR - SELECT p.id + SELECT p.id FROM information_schema.processlist p - WHERE USER = 'sorter' + WHERE USER = 'sorter' AND TIME >= 30; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN vCursor; l: LOOP @@ -60644,7 +60648,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlPreparedCount_check`() BEGIN DECLARE vPreparedCount INTEGER; - SELECT VARIABLE_VALUE INTO vPreparedCount + SELECT VARIABLE_VALUE INTO vPreparedCount FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%'; @@ -60652,7 +60656,7 @@ BEGIN CALL `vn`.`mail_insert`('cau@verdnatura.es', NULL, 'Problemas BBDD prepared_stmt_count', - CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', + CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', vPreparedCount, ', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.') ); @@ -60679,37 +60683,37 @@ BEGIN DECLARE newShelving VARCHAR(3); DECLARE vCode VARCHAR(3); - + SELECT MAX(code) INTO vCode FROM vn.shelving WHERE isPrinted = FALSE; - + SET @a1 := ASCII(MID(vCode,1,1)); SET @a2 := ASCII(MID(vCode,2,1)); SET @a3 := ASCII(MID(vCode,3,1)) + 1; - + IF @a3 > 90 THEN - + SET @a3 = 65; SET @a2 = @a2 + 1; - + IF @a2 > 90 THEN - + SET @a2 = 65; SET @a1 = @a1 + 1; - + IF @a1 > 90 THEN - + SET @a1 = 65; - + END IF; - + END IF; - + END IF; SET newShelving = CHAR(@a1,@a2,@a3 USING utf8); - + INSERT INTO vn.shelving(code) VALUES(newShelving); END ;; @@ -60738,18 +60742,18 @@ BEGIN * @param descripcion Texto de la observacion */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vTableCode,'Observation'); - + IF ISNULL(vTableName) THEN CALL util.throw('CODE_NOT_FOUND'); END IF; - + SET @qryLog := CONCAT( 'INSERT INTO ', vTableName, ' (originFk, userFk, description)', ' VALUES (', vOriginFk, ', ', account.myUser_getId(), ', "', vDescription, '")' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; DEALLOCATE PREPARE stmt; @@ -60779,15 +60783,15 @@ BEGIN DECLARE vDeliveryMethod INT; DECLARE vClient INT; - + SELECT deliveryMethodFk INTO vDeliveryMethod - FROM vn.agencyMode + FROM vn.agencyMode WHERE id = vAgencyMode; - + SELECT clientFk INTO vClient FROM vn.address WHERE id = vAddress; - + INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app) VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp); @@ -60813,7 +60817,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `orderDelete`(IN vId INT) BEGIN DELETE FROM hedera.`order` where id = vId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60840,7 +60844,7 @@ BEGIN DECLARE vOrderId INT; CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId); SELECT vOrderId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60860,7 +60864,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT) BEGIN - SELECT + SELECT o.id, o.itemFk, i.description, @@ -60886,7 +60890,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( IN vClient INT, IN vDate DATE, IN vCompany INT, @@ -60905,20 +60909,20 @@ BEGIN SET vGraceDays = IF(vIsAllInvoiceable ,0, 30); SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: + + /* Clientes especiales: 3240 MADEFLOR 992 JAVIER FELIU 4 TONI VENDRELL */ - + IF vClient IN (992, 3240, 4) THEN - + SET vGraceDays = 365; - + END IF; /* Fin clientes especiales */ - + SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY); DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; @@ -60942,22 +60946,22 @@ BEGIN FROM tmp.packageToInvoice GROUP BY itemFk HAVING totalQuantity > 0; - + SELECT COUNT(*) INTO vIsInvoiceable FROM tmp.packageToInvoicePositives; IF vIsInvoiceable THEN - CALL ticket_add(vClient, + CALL ticket_add(vClient, vDateEnd, - vWarehouse, - vCompany, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouse, + vCompany, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); @@ -60966,44 +60970,44 @@ BEGIN packagingFk, quantity, pvp) - SELECT vNewTicket, - pti.packagingFk, - - SUM(pti.quantity) AS totalQuantity, + SELECT vNewTicket, + pti.packagingFk, + - SUM(pti.quantity) AS totalQuantity, pti.price FROM tmp.packageToInvoice pti - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY packagingFk HAVING totalQuantity; INSERT INTO sale( ticketFk, - itemFk, - concept, - quantity, + itemFk, + concept, + quantity, price ) - SELECT vNewTicket, - pti.itemFk, - i.name as concept, - sum(pti.quantity) as totalQuantity, + SELECT vNewTicket, + pti.itemFk, + i.name as concept, + sum(pti.quantity) as totalQuantity, pti.price FROM tmp.packageToInvoice pti JOIN item i ON i.id = pti.itemFk LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY pti.itemFk HAVING totalQuantity; - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61029,7 +61033,7 @@ BEGIN WHERE mm.valor = 1 -- Listo para imprimir AND mm.stateFk = 9 -- Encajando AND m.Id_Ticket = ticketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61051,15 +61055,15 @@ BEGIN DECLARE valueFk INT; DECLARE encajando INT DEFAULT 9; - - SELECT valor INTO valueFk - FROM vn2008.Movimientos_mark - WHERE Id_Movimiento = saleFk + + SELECT valor INTO valueFk + FROM vn2008.Movimientos_mark + WHERE Id_Movimiento = saleFk AND stateFk = encajando; - + SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3; - - REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) + + REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) VALUES(saleFk,valueFk,account.myUser_getId(),encajando); @@ -61133,34 +61137,34 @@ BEGIN DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; DECLARE vMaxId INT; DECLARE vCode VARCHAR(8); - + SET vColumn = vFromColumn; SET vRow = vFromRow; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + SELECT MAX(id) INTO vMaxId FROM vn.parking; WHILE vColumn <= vToColumn DO - + WHILE vRow <= vToRow DO - + INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder) VALUES (vColumn, vRow, vSectorFk, vCode, vColumn * 100 + vRow ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET vRow = vRow + 1; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SET vRow = vFromRow; SET vColumn = vColumn + 1; - + SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn; END ;; @@ -61185,59 +61189,59 @@ BEGIN DECLARE vRow INT; DECLARE vCode VARCHAR(8); DECLARE i INT; - + IF vToRow < vFromRow THEN - + SET vRow = vFromRow; - + WHILE vRow >= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10)) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow - 1; - + END WHILE; ELSE - + SET vRow = vFromRow; - + WHILE vRow <= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow + 1; - + END WHILE; - - + + END IF; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61261,28 +61265,28 @@ BEGIN DECLARE vColumn INT; DECLARE vLetters VARCHAR(200); DECLARE vLettersLength INT; - + SET vColumn = vStart; SET vRow = 1; SET vLetters = 'ABCDEF'; SET vLettersLength = LENGTH(vLetters); - + WHILE vColumn <= vEnd DO - + REPLACE vn.parking(`column`, `row`, `code`, sectorFk) VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk); - + SET vRow = vRow + 1; - + IF vRow > vLettersLength THEN - + SET vRow = 1; SET vColumn = vColumn + 1; - + END IF; - + END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61300,29 +61304,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT) -BEGIN - - /* - * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor - */ - - UPDATE vn.parking p - JOIN ( - SELECT code, - @orden := @orden + 10 AS po - FROM ( - SELECT c.prepOrder, - p.code, - @orden := 0, - IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , - CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication - FROM vn.parking p - JOIN vn.sector s ON s.id = p.sectorFk - JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci - WHERE s.warehouseFk = vWarehouseFk) sub - ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code - SET p.pickingOrder = sub2.po; - +BEGIN + + /* + * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor + */ + + UPDATE vn.parking p + JOIN ( + SELECT code, + @orden := @orden + 10 AS po + FROM ( + SELECT c.prepOrder, + p.code, + @orden := 0, + IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , + CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication + FROM vn.parking p + JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci + WHERE s.warehouseFk = vWarehouseFk) sub + ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code + SET p.pickingOrder = sub2.po; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61340,18 +61344,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`() -BEGIN - - /* - * Require la tabla tmp.ticket(id,clientFk) - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.client; - CREATE TEMPORARY TABLE tmp.client - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT DISTINCT clientFk id - FROM tmp.ticket; +BEGIN + + /* + * Require la tabla tmp.ticket(id,clientFk) + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.client; + CREATE TEMPORARY TABLE tmp.client + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT DISTINCT clientFk id + FROM tmp.ticket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61369,25 +61373,25 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareTicketList`(vStartingDate DATETIME, vEndingDate DATETIME) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket; - CREATE TEMPORARY TABLE tmp.productionTicket - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk - FROM vn.ticket t - LEFT JOIN vn.ticketState ts ON ts.ticket = t.id - JOIN vn.client c ON c.id = t.clientFk - WHERE c.typeFk IN ('normal','handMaking','internalUse') - AND ( - t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate - OR ( - ts.alertLevel < 3 - AND t.shipped >= vStartingDate - AND t.shipped < util.VN_CURDATE() - ) - ); +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket; + CREATE TEMPORARY TABLE tmp.productionTicket + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk, t.clientFk + FROM vn.ticket t + LEFT JOIN vn.ticketState ts ON ts.ticket = t.id + JOIN vn.client c ON c.id = t.clientFk + WHERE c.typeFk IN ('normal','handMaking','internalUse') + AND ( + t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate + OR ( + ts.alertLevel < 3 + AND t.shipped >= vStartingDate + AND t.shipped < util.VN_CURDATE() + ) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61480,14 +61484,14 @@ BEGIN /** * Comprueba si la impresora pertenece al sector * - * @param vLabelerFk id de la impresora + * @param vLabelerFk id de la impresora * @param vSector sector a comprobar */ DECLARE isPrinterInNewSector BOOL; IF vLabelerFk IS NOT NULL THEN SELECT COUNT(sectorFK) INTO isPrinterInNewSector - FROM vn.printer p + FROM vn.printer p WHERE id = vLabelerFk AND sectorFk = vSector; IF !isPrinterInNewSector THEN @@ -61888,7 +61892,7 @@ BEGIN `yearMonth` INT ) ENGINE = MEMORY; - + WHILE vDated <= vEnded DO INSERT INTO tmp.rangeDate SET `dated` = vDated, @@ -61898,7 +61902,7 @@ BEGIN `day` = DAY(vDated), `week` = WEEK(vDated, 1), `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); END WHILE; END ;; @@ -61921,14 +61925,14 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `rankingTeamByQuarter`(vYear INT, vQ BEGIN DECLARE vMinimumSalesByQuarter INT; - + SELECT minimumSalesByQuarter INTO vMinimumSalesByQuarter FROM commissionConfig; - + DROP TEMPORARY TABLE IF EXISTS tmp.rankingTeam; CREATE TEMPORARY TABLE tmp.rankingTeam - (PRIMARY KEY(departmentFk)) ENGINE = MEMORY - SELECT + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + SELECT (sub1.importe - sub2.importe) / IF ((sub1.importe - sub2.importe) > 0,sub3.countPeople,1) AS diferencia, CONCAT(sub1.name, '(', @@ -61938,14 +61942,14 @@ BEGIN ')') AS teamPeople, sub1.departmentFk AS departmentFk FROM - (((SELECT + (((SELECT SUM(sub.importe) AS importe, sub.name AS name, sub.año AS año, sub.departmentFk AS departmentFk, COUNT(*) peopleMinSale FROM - (SELECT + (SELECT SUM(v.portfolioWeight) AS importe, d.`name`, v.año, @@ -61960,7 +61964,7 @@ BEGIN GROUP BY v.Id_Trabajador HAVING importe >= vMinimumSalesByQuarter) sub GROUP BY sub.departmentFk) sub1 - JOIN (SELECT + JOIN (SELECT SUM(v.portfolioWeight) AS importe, d.name, wd.departmentFk @@ -62006,7 +62010,7 @@ BEGIN * @param vDated fecha para la cual calcula la tarifa * @param vWarehouseFk warehouse para el cual calcula la tafia * @return tmp.rate(rate0, rate1, rate2, rate3) - */ + */ DROP TEMPORARY TABLE IF EXISTS tRate; CREATE TEMPORARY TABLE tRate SELECT rate0, rate1, rate2, rate3 @@ -62014,13 +62018,13 @@ BEGIN WHERE dated <= vDated AND warehouseFk = vWarehouseFk ORDER BY dated DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.rate; CREATE TEMPORARY TABLE tmp.rate ENGINE = MEMORY SELECT * FROM ( - SELECT * FROM tRate + SELECT * FROM tRate UNION ALL SELECT rate0, rate1, rate2, rate3 FROM rateConfig ) sub2 @@ -62053,13 +62057,13 @@ BEGIN WHERE dated <= vLanded AND warehouseFk = vWarehouseFk ORDER BY dated DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.rate; CREATE TEMPORARY TABLE tmp.rate ENGINE = MEMORY SELECT * FROM ( - SELECT * FROM tRate + SELECT * FROM tRate UNION ALL SELECT rate0, rate1, rate2, rate3 FROM rateConfig ) sub2 @@ -62093,7 +62097,7 @@ BEGIN CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate); DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook; - + CREATE TEMPORARY TABLE tmp.recipeCook SELECT *, @counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter, @@ -62111,22 +62115,22 @@ BEGIN IFNULL((i.inkFk = r.inkFk ) ,0) + IFNULL((i.size = r.size) ,0) + IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0) - + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + IFNULL((i.typeFk = r.typeFk),0) as matches, i.typeFk, rl.previousSelected - FROM vn.recipe r + FROM vn.recipe r JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0) OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0)) OR i.typeFk <=> r.typeFk JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected FROM vn.recipe_log - GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk + GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk AND rl.log_element = r.element AND rl.selected_ItemFk = i.id WHERE r.itemFk = vItemFk - AND a.available > vBunchesQuantity * r.quantity + AND a.available > vBunchesQuantity * r.quantity UNION ALL SELECT 100 itemFk, CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName, @@ -62143,15 +62147,15 @@ BEGIN WHERE r.itemFk = vItemFk GROUP BY r.element ) sub - + ORDER BY element, matches DESC, previousSelected DESC; - - SELECT * + + SELECT * FROM tmp.recipeCook WHERE counter < 6 - OR itemFk = 100 + OR itemFk = 100 ; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62176,71 +62180,71 @@ BEGIN DECLARE vShipped DATE; DECLARE vEntryFk INT; DECLARE vTravelFk INT; - + CALL cache.last_buy_refresh(FALSE); - - SELECT warehouseFk, shipped + + SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; UPDATE vn.ticket t JOIN vn.item i ON i.id = vItemFk SET t.nickname = CONCAT(vQuantity,' ',i.longName) WHERE t.id = vTicketFk; - + SELECT b.buyingValue INTO vLastCost FROM vn.buy b JOIN cache.last_buy lb ON lb.buy_id = b.id WHERE lb.item_id = vItemFk ORDER BY (lb.warehouse_id = vWarehouseFk) DESC LIMIT 1; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost FROM vn.item i WHERE i.id = vItemFk; - /* + /* SELECT tr.id INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse w ON w.id = tr.warehouseOutFk WHERE tr.warehouseInFk = vWarehouseFk AND tr.landed = vShipped AND w.name = 'Confeccion'; - + IF IFNULL(vTravelFk,0) = 0 THEN - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk) SELECT vShipped, vShipped, vWarehouseFk, w.id, am.id - FROM vn.warehouse w - JOIN vn.agencyMode am + FROM vn.warehouse w + JOIN vn.agencyMode am WHERE w.name = 'Confeccion' AND am.name = 'DIRECTO PROVEEDOR'; - + SET vTravelFk = LAST_INSERT_ID(); - - END IF; - + + END IF; + SELECT e.id INTO vEntryFk FROM vn.entry e JOIN vn.supplier s ON s.id = supplierFk WHERE e.travelFk = vTravelFk AND s.name = 'Confeccion Natural' AND e.isRaid = FALSE; - + IF IFNULL(vEntryFk,0) = 0 THEN - + INSERT INTO vn.entry(supplierFk, evaNotes, travelFk, companyFk) SELECT s.id, t.nickname, vTravelFk, c.id FROM vn.supplier s JOIN vn.ticket t ON t.id = vTicketFk - JOIN vn.company c ON c.code = 'VNL' + JOIN vn.company c ON c.code = 'VNL' WHERE s.name = 'Confeccion Natural'; - + SET vEntryFk = LAST_INSERT_ID(); - + END IF; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, buyingValue, packageFk, packing, grouping) SELECT vEntryFk, b.itemFk, vQuantity, b.buyingValue, b.packageFk, b.packing, b.grouping FROM cache.last_buy lb @@ -62267,7 +62271,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `refund`(IN vOriginTicket INT, OUT vNewTicket INT) BEGIN - + DECLARE vDone BIT DEFAULT 0; DECLARE vCustomer MEDIUMINT; DECLARE vWarehouse TINYINT; @@ -62282,26 +62286,26 @@ BEGIN DECLARE vSaleNew INT; DECLARE vSaleMain INT; DECLARE vZoneFk INT; - + DECLARE vRsMainTicket CURSOR FOR SELECT id, itemFk, - quantity, concept, price, discount - FROM vn.sale + FROM vn.sale WHERE ticketFk = vOriginTicket; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - + SELECT id INTO vRefundAgencyMode FROM agencyMode WHERE `name` = 'ABONO'; - SELECT clientFk, warehouseFk, companyFk, addressFk + SELECT clientFk, warehouseFk, companyFk, addressFk INTO vCustomer, vWarehouse, vCompany, vAddress - FROM ticket + FROM ticket WHERE id = vOriginTicket; - - SELECT id INTO vZoneFk + + SELECT id INTO vZoneFk FROM zone WHERE agencyModeFk = vRefundAgencyMode LIMIT 1; - + INSERT INTO vn2008.Tickets ( Id_Cliente, Fecha, @@ -62328,26 +62332,26 @@ BEGIN SET vNewTicket = LAST_INSERT_ID(); - SET vDone := 0; + SET vDone := 0; OPEN vRsMainTicket ; FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount; WHILE NOT vDone DO - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount) VALUES( vNewTicket, vItemFk, vQuantity, vConcept, vPrice, vDiscount ); - + SET vSaleNew = LAST_INSERT_ID(); - - INSERT INTO vn.saleComponent(saleFk,componentFk,`value`) - SELECT vSaleNew,componentFk,`value` - FROM vn.saleComponent + + INSERT INTO vn.saleComponent(saleFk,componentFk,`value`) + SELECT vSaleNew,componentFk,`value` + FROM vn.saleComponent WHERE saleFk = vSaleMain; - + FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount; - + END WHILE; - CLOSE vRsMainTicket; + CLOSE vRsMainTicket; END ;; DELIMITER ; @@ -62382,12 +62386,12 @@ BEGIN * usar vn.saleTracking_Replace * */ - - REPLACE INTO vn2008.Movimientos_mark(Id_Movimiento, valor, original_quantity, Id_Trabajador, stateFk) + + REPLACE INTO vn2008.Movimientos_mark(Id_Movimiento, valor, original_quantity, Id_Trabajador, stateFk) VALUES(idMovimiento,detalle,originalQuantity,idTrabajador,stateFk); - /*INSERT INTO vn.ticketLog (originFk, userFk, action , description) + /*INSERT INTO vn.ticketLog (originFk, userFk, action , description) VALUES(originFk, userFk, actionString, description);*/ - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62405,53 +62409,53 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `reportLabelCollection_get`(vParam INT) -BEGIN -/** - * Obtiene los datos de etiquetas a partir de de un ticket o colección. - * - * @param vParam Ticket/Colección del que sacar los datos - */ - DECLARE vIsCollection BOOL; - - SELECT IF(id, TRUE, FALSE) INTO vIsCollection - FROM vn.collection c - WHERE id = vParam; - - SELECT c.itemPackingTypeFk, - CONCAT(tc.collectionFk, ' ', LEFT(cc.code, 4)) color, - CONCAT(tc.collectionFk, ' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.`level`) levelV, - tc.ticketFk, - LEFT(COALESCE(et.description, zo.name, am.name),12) agencyDescription, - am.name, - t.clientFk, - CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5, 2)), 'm³') m3 , - CAST(IF(ic.code = 'plant', CONCAT(MAX(i.`size`),' cm'), COUNT(*)) AS CHAR) size, - w.code workerCode, - tt.labelCount, - IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.`hour`)) agencyHour, - t.shipped, - COUNT(*) lineCount, - t.nickName - FROM ticket t - JOIN ticketCollection tc ON tc.ticketFk = t.id - JOIN collection c ON c.id = tc.collectionFk - LEFT JOIN collectionColors cc ON cc.shelve = tc.`level` - AND cc.wagon = tc.wagon - AND cc.trainFk = c.trainFk - JOIN sale s ON s.ticketFk = t.id - LEFT JOIN saleVolume sv ON sv.saleFk = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN worker w ON w.id = c.workerFk - JOIN agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN ticketTrolley tt ON tt.ticket = t.id - LEFT JOIN `zone` zo ON t.zoneFk = zo.id - LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN expeditionTruck et ON et.id = rm.expeditionTruckFk - WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) - GROUP BY t.id - ORDER BY cc.`code`; +BEGIN +/** + * Obtiene los datos de etiquetas a partir de de un ticket o colección. + * + * @param vParam Ticket/Colección del que sacar los datos + */ + DECLARE vIsCollection BOOL; + + SELECT IF(id, TRUE, FALSE) INTO vIsCollection + FROM vn.collection c + WHERE id = vParam; + + SELECT c.itemPackingTypeFk, + CONCAT(tc.collectionFk, ' ', LEFT(cc.code, 4)) color, + CONCAT(tc.collectionFk, ' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.`level`) levelV, + tc.ticketFk, + LEFT(COALESCE(et.description, zo.name, am.name),12) agencyDescription, + am.name, + t.clientFk, + CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5, 2)), 'm³') m3 , + CAST(IF(ic.code = 'plant', CONCAT(MAX(i.`size`),' cm'), COUNT(*)) AS CHAR) size, + w.code workerCode, + tt.labelCount, + IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.`hour`)) agencyHour, + t.shipped, + COUNT(*) lineCount, + t.nickName + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + JOIN collection c ON c.id = tc.collectionFk + LEFT JOIN collectionColors cc ON cc.shelve = tc.`level` + AND cc.wagon = tc.wagon + AND cc.trainFk = c.trainFk + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN worker w ON w.id = c.workerFk + JOIN agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN ticketTrolley tt ON tt.ticket = t.id + LEFT JOIN `zone` zo ON t.zoneFk = zo.id + LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN expeditionTruck et ON et.id = rm.expeditionTruckFk + WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) + GROUP BY t.id + ORDER BY cc.`code`; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62468,71 +62472,71 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`( - vReportName VARCHAR(100), - vPrinterFk INT, - vUserFk INT, - vParams JSON, - vPriorityName VARCHAR(100) +CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`( + vReportName VARCHAR(100), + vPrinterFk INT, + vUserFk INT, + vParams JSON, + vPriorityName VARCHAR(100) ) -BEGIN -/** - * Inserts in the print queue the report to be printed and the necessary parameters for this - * one taking into account the paper size of both the printer and the report. - * - * @param vReportName the report to be printed. - * @param vPrinterFk the printer selected. - * @param vUserFk user id. - * @param vParams Json with report parameters. - * @param vPriorityName the printing priority. - */ - DECLARE vI INT DEFAULT 0; - DECLARE vKeys TEXT DEFAULT JSON_KEYS(vParams); - DECLARE vLength INT DEFAULT JSON_LENGTH(vKeys); - DECLARE vKey VARCHAR(255); - DECLARE vVal VARCHAR(255); - DECLARE vPrintQueueFk INT; - DECLARE vIsTheReportReal INT; - DECLARE vReportSize VARCHAR(255); - DECLARE vIsThePrinterReal INT; - DECLARE vPrinteSize VARCHAR(255); - - SELECT id, paperSizeFk INTO vIsTheReportReal, vReportSize FROM report WHERE name = vReportName; - SELECT id, paperSizeFk INTO vIsThePrinterReal, vPrinteSize FROM printer WHERE id = vPrinterFk; - - IF vIsThePrinterReal IS NULL THEN - CALL util.throw('printerNotExists'); - END IF; - - IF vIsTheReportReal IS NULL THEN - CALL util.throw('reportNotExists'); - END IF; - - IF vReportSize <> vPrinteSize THEN - CALL util.throw('incorrectSize'); - END IF; - - START TRANSACTION; - INSERT INTO printQueue - SET printerFk = vPrinterFk, - priorityFk = (SELECT qp.id FROM queuePriority qp WHERE qp.code = vPriorityName), - reportFk = (SELECT r.id FROM report r WHERE r.name = vReportName), - workerFk = vUserFk; - - SET vPrintQueueFk = LAST_INSERT_ID(); - - WHILE vI < vLength DO - SET vKey = JSON_VALUE(vKeys, CONCAT('$[', vI ,']')); - SET vVal = JSON_VALUE(vParams, CONCAT('$.', vKey)); - - INSERT INTO printQueueArgs - SET printQueueFk = vPrintQueueFk, - name = vKey, - value = vVal; - - SET vI = vI + 1; - END WHILE; - COMMIT; +BEGIN +/** + * Inserts in the print queue the report to be printed and the necessary parameters for this + * one taking into account the paper size of both the printer and the report. + * + * @param vReportName the report to be printed. + * @param vPrinterFk the printer selected. + * @param vUserFk user id. + * @param vParams Json with report parameters. + * @param vPriorityName the printing priority. + */ + DECLARE vI INT DEFAULT 0; + DECLARE vKeys TEXT DEFAULT JSON_KEYS(vParams); + DECLARE vLength INT DEFAULT JSON_LENGTH(vKeys); + DECLARE vKey VARCHAR(255); + DECLARE vVal VARCHAR(255); + DECLARE vPrintQueueFk INT; + DECLARE vIsTheReportReal INT; + DECLARE vReportSize VARCHAR(255); + DECLARE vIsThePrinterReal INT; + DECLARE vPrinteSize VARCHAR(255); + + SELECT id, paperSizeFk INTO vIsTheReportReal, vReportSize FROM report WHERE name = vReportName; + SELECT id, paperSizeFk INTO vIsThePrinterReal, vPrinteSize FROM printer WHERE id = vPrinterFk; + + IF vIsThePrinterReal IS NULL THEN + CALL util.throw('printerNotExists'); + END IF; + + IF vIsTheReportReal IS NULL THEN + CALL util.throw('reportNotExists'); + END IF; + + IF vReportSize <> vPrinteSize THEN + CALL util.throw('incorrectSize'); + END IF; + + START TRANSACTION; + INSERT INTO printQueue + SET printerFk = vPrinterFk, + priorityFk = (SELECT qp.id FROM queuePriority qp WHERE qp.code = vPriorityName), + reportFk = (SELECT r.id FROM report r WHERE r.name = vReportName), + workerFk = vUserFk; + + SET vPrintQueueFk = LAST_INSERT_ID(); + + WHILE vI < vLength DO + SET vKey = JSON_VALUE(vKeys, CONCAT('$[', vI ,']')); + SET vVal = JSON_VALUE(vParams, CONCAT('$.', vKey)); + + INSERT INTO printQueueArgs + SET printQueueFk = vPrintQueueFk, + name = vKey, + value = vVal; + + SET vI = vI + 1; + END WHILE; + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62551,16 +62555,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `riskAllClients`(maxRiskDate DATE) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY SELECT id Id_Cliente, null grade FROM vn.client; - + CALL vn2008.risk_vs_client_list(maxRiskDate); - - SELECT + + SELECT c.RazonSocial, c.Id_Cliente, c.Credito, @@ -62572,7 +62576,7 @@ BEGIN JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente GROUP BY c.Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -62631,25 +62635,25 @@ BEGIN DECLARE vM3 INT; DECLARE vKg INT; DECLARE vMatricula varchar(50); - + SELECT sum(packages) as bultos INTO vPackages - FROM vn.ticket t + FROM vn.ticket t WHERE routeFk = vRouteFk; - + SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight) INTO vM3, vKg FROM vn.saleVolume sv WHERE sv.routeFk = vRouteFk; - + SELECT v.numberPlate as matricula INTO vMatricula - FROM vn.route r + FROM vn.route r JOIN vn.vehicle v ON r.vehicleFk = v.id WHERE r.id = vRouteFk; - + SELECT vRouteFk as Ruta, - vPackages as Bultos, + vPackages as Bultos, vM3 as m3, vKg as Kg, vMatricula as Matricula; @@ -62679,12 +62683,12 @@ BEGIN SET vDate = TIMESTAMPADD(DAY,-1,vDate); DROP TEMPORARY TABLE IF EXISTS tmp.routesMonitor; - + CREATE TEMPORARY TABLE tmp.routesMonitor (INDEX (routeFk)) ENGINE = MEMORY SELECT DISTINCT(t.routeFk) routeFk - FROM vn.ticket t + FROM vn.ticket t WHERE t.shipped BETWEEN vDate AND vDateEND AND t.routeFk IS NOT NULL; @@ -62695,7 +62699,7 @@ BEGIN UPDATE routesMonitor rm JOIN route r ON r.id = rm.routeFk JOIN agencyMode a ON a.id = r.agencyModeFk - SET rm.`name` = a.name, + SET rm.`name` = a.name, rm.ticketFree = 0, rm.ticketProduction = 0, rm.ticketPacked = 0, @@ -62712,7 +62716,7 @@ BEGIN ) sub ON sub.routeFk = rm.routeFk SET rm.ticketFree = sub.ticketFree; - UPDATE routesMonitor rm + UPDATE routesMonitor rm JOIN(SELECT t.routeFk, COUNT(*) AS ticketPacked FROM vn.ticket t JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk @@ -62720,7 +62724,7 @@ BEGIN JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk JOIN state s ON s.id = tt.stateFk AND s.alertLevel = 2 GROUP BY t.routeFk - ) sub ON sub.routeFk = rm.routeFk + ) sub ON sub.routeFk = rm.routeFk SET rm.ticketPacked = sub.ticketPacked; UPDATE routesMonitor rm @@ -62747,7 +62751,7 @@ BEGIN JOIN( SELECT t.routeFk, SUM(sv.volume) AS m3 FROM vn.ticket t JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk - JOIN vn.saleVolume sv ON sv.ticketFk = t.id + JOIN vn.saleVolume sv ON sv.ticketFk = t.id GROUP BY t.routeFk ) sub ON sub.routeFk = rm.routeFk SET rm.m3 = sub.m3; @@ -62757,15 +62761,15 @@ BEGIN FROM vn.ticket t JOIN tmp.routesMonitor rm ON rm.routeFk = t.routeFk JOIN vn.expedition e ON e.ticketFk = t.id - JOIN vn.packaging pk ON pk.id = e.packagingFk + JOIN vn.packaging pk ON pk.id = e.packagingFk GROUP BY t.routeFk - ) sub ON sub.routeFk = rm.routeFk - SET rm.m3boxes = sub.m3boxes; + ) sub ON sub.routeFk = rm.routeFk + SET rm.m3boxes = sub.m3boxes; UPDATE routesMonitor rm - JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk SET rm.etd = et.ETD; - + DROP TEMPORARY TABLE tmp.routesMonitor; END ;; DELIMITER ; @@ -62786,11 +62790,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `routeSetOk`( vRouteFk INT) BEGIN - + UPDATE vn.route r SET r.isOk = 1 WHERE r.id = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62855,17 +62859,17 @@ proc: BEGIN IF vIsFreelance THEN INSERT INTO routeCommission ( - routeFk, - workCenterFk, - freelanceYearlyM3, - cat4m3, + routeFk, + workCenterFk, + freelanceYearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, rc.freelanceM3 * IF( - IFNULL(r.m3, 0) >= rc.freelanceMinM3, - IFNULL(r.m3, 0), + IFNULL(r.m3, 0) >= rc.freelanceMinM3, + IFNULL(r.m3, 0), 0), rc.distributionCat4M3 * IFNULL(r.m3, 0), rc.distributionCat5M3 * IFNULL(r.m3, 0) @@ -62877,20 +62881,20 @@ proc: BEGIN AND r.commissionWorkCenterFk; ELSE INSERT INTO routeCommission ( - routeFk, - workCenterFk, - km, - m3, - yearlyKm, - yearlyM3, - cat4m3, + routeFk, + workCenterFk, + km, + m3, + yearlyKm, + yearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, - (r.kmEnd - r.kmStart) * + (r.kmEnd - r.kmStart) * IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight), - IFNULL(r.m3, 0) * + IFNULL(r.m3, 0) * IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4), (r.kmEnd - r.kmStart) * rc.kmYearly, IFNULL(r.m3, 0) * rc.m3Yearly, @@ -62927,7 +62931,7 @@ proc: BEGIN /** * Recalculates modified route. */ - + DECLARE vDone BOOL; DECLARE vRouteFk INT; @@ -62936,7 +62940,7 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN DO RELEASE_LOCK('vn.route_doRecalc'); @@ -62984,62 +62988,62 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `route_getTickets`(vRouteFk INT) -BEGIN -/** - * Pasado un RouteFk devuelve la información - * de sus tickets. - * - * @param vRouteFk - * - * @select Información de los tickets - */ - - SELECT - t.id AS Id, - t.clientFk AS Client, - a.id AS Address, - a.nickname AS ClientName, - t.packages AS Packages, - a.street AS AddressName, - a.postalCode AS PostalCode, - a.city AS City, - sub2.itemPackingTypeFk AS PackingType, - c.phone AS ClientPhone, - c.mobile AS ClientMobile, - a.phone AS AddressPhone, - a.mobile AS AddressMobile, - tl.longitude AS Longitude, - tl.latitude AS Latitude, - wm.mediaValue AS SalePersonPhone, - tob.Note AS Note, - t.isSigned AS Signed - FROM ticket t - JOIN client c ON t.clientFk = c.id - JOIN address a ON t.addressFk = a.id - LEFT JOIN ticketLocation tl ON tl.ticketFk = t.id - LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk - LEFT JOIN - (SELECT tob.description AS Note, t.id - FROM ticketObservation tob - JOIN ticket t ON tob.ticketFk = t.id - JOIN observationType ot ON ot.id = tob.observationTypeFk - WHERE t.routeFk = vRouteFk - AND ot.code = 'delivery' - )tob ON tob.id = t.id - LEFT JOIN - (SELECT sub.ticketFk, - CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk - FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - WHERE t.routeFk = vRouteFk - GROUP BY t.id,i.itemPackingTypeFk)sub - GROUP BY sub.ticketFk - ) sub2 ON sub2.ticketFk = t.id - WHERE t.routeFk = vRouteFk - GROUP BY t.id - ORDER BY t.priority; +BEGIN +/** + * Pasado un RouteFk devuelve la información + * de sus tickets. + * + * @param vRouteFk + * + * @select Información de los tickets + */ + + SELECT + t.id AS Id, + t.clientFk AS Client, + a.id AS Address, + a.nickname AS ClientName, + t.packages AS Packages, + a.street AS AddressName, + a.postalCode AS PostalCode, + a.city AS City, + sub2.itemPackingTypeFk AS PackingType, + c.phone AS ClientPhone, + c.mobile AS ClientMobile, + a.phone AS AddressPhone, + a.mobile AS AddressMobile, + tl.longitude AS Longitude, + tl.latitude AS Latitude, + wm.mediaValue AS SalePersonPhone, + tob.Note AS Note, + t.isSigned AS Signed + FROM ticket t + JOIN client c ON t.clientFk = c.id + JOIN address a ON t.addressFk = a.id + LEFT JOIN ticketLocation tl ON tl.ticketFk = t.id + LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk + LEFT JOIN + (SELECT tob.description AS Note, t.id + FROM ticketObservation tob + JOIN ticket t ON tob.ticketFk = t.id + JOIN observationType ot ON ot.id = tob.observationTypeFk + WHERE t.routeFk = vRouteFk + AND ot.code = 'delivery' + )tob ON tob.id = t.id + LEFT JOIN + (SELECT sub.ticketFk, + CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk + FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.routeFk = vRouteFk + GROUP BY t.id,i.itemPackingTypeFk)sub + GROUP BY sub.ticketFk + ) sub2 ON sub2.ticketFk = t.id + WHERE t.routeFk = vRouteFk + GROUP BY t.id + ORDER BY t.priority; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63179,7 +63183,7 @@ BEGIN AND rm.año = vYear AND rm.mes = vMonth; - -- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta + -- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta UPDATE bi.rutasBoard r JOIN ( SELECT t.routeFk, sum(s.quantity * sc.value) practicoTotal @@ -63191,7 +63195,7 @@ BEGIN JOIN component c ON c.id = sc.componentFk JOIN componentType ct ON ct.id = c.typeFk WHERE ct.type = 'agencia' - AND tm.year = vYear + AND tm.year = vYear AND tm.month = vMonth GROUP BY r.id ) sub ON sub.routeFk = r.Id_Ruta @@ -63200,7 +63204,7 @@ BEGIN -- Coste TEORICO de una caja "virtual" para cada ruta, teniendo en cuenta que hay carros, pallets, etc UPDATE bi.rutasBoard r JOIN ( - SELECT t.routeFk, + SELECT t.routeFk, SUM(t.zonePrice/ ebv.ratio)/ count(*) AS BultoTeoricoMedio FROM ticket t JOIN route r ON r.id = t.routeFk @@ -63210,7 +63214,7 @@ BEGIN JOIN address ad ON ad.id = t.addressFk JOIN client c ON c.id = ad.clientFk LEFT JOIN zone z ON z.id = t.zoneFk - WHERE tm.year = vYear + WHERE tm.year = vYear AND tm.month = vMonth AND z.isVolumetric = FALSE GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk @@ -63219,7 +63223,7 @@ BEGIN -- Coste VOLUMETRICO TEORICO de una caja "virtual" para cada ruta UPDATE bi.rutasBoard r JOIN ( - SELECT t.routeFk, + SELECT t.routeFk, SUM(freight) AS BultoTeoricoMedio FROM ticket t JOIN route r ON r.id = t.routeFk @@ -63227,7 +63231,7 @@ BEGIN JOIN saleVolume sf ON sf.ticketFk = t.id JOIN client c ON c.id = t.clientFk JOIN zone z ON z.id = t.zoneFk - WHERE tm.year = vYear + WHERE tm.year = vYear AND tm.month = vMonth AND z.isVolumetric != FALSE GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk @@ -63236,14 +63240,14 @@ BEGIN -- La diferencia entre el teorico y el practico se deberia de cobrar en greuges, cada noche UPDATE bi.rutasBoard r JOIN ( - SELECT t.routeFk, + SELECT t.routeFk, Sum(g.amount) AS greuge FROM ticket t JOIN route r ON r.id = t.routeFk JOIN time tm ON tm.dated = r.created JOIN greuge g ON g.ticketFk = t.id JOIN greugeType gt ON gt.id = g.greugeTypeFk - WHERE tm.year = vYear + WHERE tm.year = vYear AND tm.month = vMonth AND gt.name = 'Diferencia portes' GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk @@ -63265,28 +63269,28 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT) -BEGIN - - /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad - * - * @param vSaleFk clave primaria de vn.sale - * @param vBuyFk clave primaria de vn.buy - */ - /*IF (SELECT COUNT(*) - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - WHERE s.id = vSaleFk - AND ic.code = 'fruit') THEN */ - - IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN - - INSERT INTO vn.saleBuy (saleFk, buyFk) - VALUES(vSaleFk, vBuyFk); - - END IF; - +BEGIN + + /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad + * + * @param vSaleFk clave primaria de vn.sale + * @param vBuyFk clave primaria de vn.buy + */ + /*IF (SELECT COUNT(*) + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE s.id = vSaleFk + AND ic.code = 'fruit') THEN */ + + IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN + + INSERT INTO vn.saleBuy (saleFk, buyFk) + VALUES(vSaleFk, vBuyFk); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63304,16 +63308,16 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGroup_add`(vSectorFk INT) -BEGIN -/** - * Añade un nuevo registro a la tabla y devuelve su id. - * - * @param vSectorFk Identificador de vn.sector - */ - INSERT INTO vn.saleGroup(userFk, sectorFk) - VALUES (account.myUser_getId(), vSectorFk); - - SELECT LAST_INSERT_ID(); +BEGIN +/** + * Añade un nuevo registro a la tabla y devuelve su id. + * + * @param vSectorFk Identificador de vn.sector + */ + INSERT INTO vn.saleGroup(userFk, sectorFk) + VALUES (account.myUser_getId(), vSectorFk); + + SELECT LAST_INSERT_ID(); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63409,19 +63413,19 @@ BEGIN IF vClientTypeFk <> 'handMaking' THEN SELECT t.id INTO vNewTicket - FROM ticket t + FROM ticket t JOIN ticketState ts ON ts.ticketFk = t.id WHERE t.addressFk = vAddressFk - AND t.warehouseFk = vWarehouseFk + AND t.warehouseFk = vWarehouseFk AND t.agencyModeFk = vAgencyModeFk AND t.landed <=> vLanded - AND t.shipped BETWEEN vShipped AND vShippedDayEnd + AND t.shipped BETWEEN vShipped AND vShippedDayEnd AND t.refFk IS NULL AND t.id <> vTicketOriginalFk AND IFNULL(ts.alertLevel,0) = 0 - LIMIT 1; + LIMIT 1; END IF; - + IF vNewTicket IS NULL THEN CALL vn.ticket_Clone(vTicketOriginalFk, vNewTicket); END IF; @@ -63430,33 +63434,33 @@ BEGIN SELECT vNewTicket, account.myUser_getId(), s.id FROM state s WHERE s.code = 'FIXING'; - + SELECT COUNT(id) INTO hasAlreadyItem FROM sale s WHERE s.ticketFk = vNewTicket AND s.itemFk = vItemFk; - + IF hasAlreadyItem = FALSE THEN - - INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) SELECT vNewTicket, itemFk, concept, vQuantity, price, discount FROM sale s WHERE s.id = vSaleFk; - + SELECT LAST_INSERT_ID() INTO vNewSale; - + INSERT INTO saleComponent(saleFk, componentFk, `value`) SELECT vNewSale, componentFk, `value` - FROM saleComponent + FROM saleComponent WHERE saleFk = vSaleFk; - + ELSE - UPDATE sale + UPDATE sale SET quantity = quantity + vQuantity WHERE ticketFk = vNewTicket AND itemFk = vItemFk; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63535,41 +63539,41 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleSplit`(vSaleFk INT, vQuantity INT) BEGIN - + DECLARE vNewSaleFk INT; - - INSERT INTO vn.sale(itemFk, - concept, - price, - discount, - quantity, - ticketFk, + + INSERT INTO vn.sale(itemFk, + concept, + price, + discount, + quantity, + ticketFk, isPriceFixed) - SELECT s.itemFk, - i.longName, - s.price, - s.discount, + SELECT s.itemFk, + i.longName, + s.price, + s.discount, vQuantity, - s.ticketFk, - s.isPriceFixed + s.ticketFk, + s.isPriceFixed FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk WHERE s.id = vSaleFk; - + UPDATE vn.sale s JOIN vn.item i ON i.id = s.itemFk SET s.quantity = s.quantity - vQuantity, s.concept = i.longName WHERE s.id = vSaleFk; - + SELECT LAST_INSERT_ID() INTO vNewSaleFk; - - INSERT INTO vn.saleComponent( saleFk, - componentFk, + + INSERT INTO vn.saleComponent( saleFk, + componentFk, value) - SELECT vNewSaleFk, - componentFk, + SELECT vNewSaleFk, + componentFk, value - FROM vn.saleComponent + FROM vn.saleComponent WHERE saleFk = vSaleFk; END ;; @@ -63598,9 +63602,9 @@ BEGIN JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vTicketFk AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; + GROUP BY s.itemFk, s.price, s.discount; - UPDATE vn.sale s + UPDATE vn.sale s JOIN salesToPreserve stp ON stp.id = s.id SET quantity = newQuantity WHERE s.ticketFk = vTicketFk; @@ -63649,17 +63653,17 @@ BEGIN OPEN cCur; myLoop: LOOP - + SET vDone = FALSE; - + FETCH cCur INTO vTicketFk; IF vDone THEN LEAVE myLoop; END IF; - + CALL vn.sales_merge(vTicketFk); - + END LOOP; CLOSE cCur; @@ -63681,28 +63685,28 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_add`(vSaleGroupFk INT) -BEGIN - - /* Inserta en vn.saleTracking las lineas de una previa - * - * @param vSaleGroupFk Identificador de vn.saleGroup - */ - - REPLACE vn.saleTracking(saleFk, - isChecked, - workerFk, - actionFk, - stateFk) - SELECT sgd.saleFk , - TRUE, - account.myUser_getId(), - a.accion_id, - s.id - FROM vn.saleGroupDetail sgd - JOIN vncontrol.accion a ON a.accion = 'SACAR' - JOIN vn.state s ON s.code = 'ON_PREPARATION' - WHERE sgd.saleGroupFk = vSaleGroupFk; - +BEGIN + + /* Inserta en vn.saleTracking las lineas de una previa + * + * @param vSaleGroupFk Identificador de vn.saleGroup + */ + + REPLACE vn.saleTracking(saleFk, + isChecked, + workerFk, + actionFk, + stateFk) + SELECT sgd.saleFk , + TRUE, + account.myUser_getId(), + a.accion_id, + s.id + FROM vn.saleGroupDetail sgd + JOIN vncontrol.accion a ON a.accion = 'SACAR' + JOIN vn.state s ON s.code = 'ON_PREPARATION' + WHERE sgd.saleGroupFk = vSaleGroupFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63720,21 +63724,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_addPreparedSaleGroup`(vSaleGroupFk INT) -BEGIN - - /** - * Inserta lineas de vn.saleTracking para un saleGroup (previa) que escanea un sacador - * - * @param vSaleGroupFk Identificador de vn.saleGroup - */ - - REPLACE vn.saleTracking(saleFk, isChecked, workerFk, actionFk, stateFk) - SELECT sgd.saleFk, TRUE, account.myUser_getId(), a.accion_id id, s.id - FROM vn.saleGroupDetail sgd - JOIN vncontrol.accion a ON a.accion = 'SACAR' - JOIN vn.state s ON s.code = 'PREPARED' - WHERE sgd.saleGroupFk = vSaleGroupFk; - +BEGIN + + /** + * Inserta lineas de vn.saleTracking para un saleGroup (previa) que escanea un sacador + * + * @param vSaleGroupFk Identificador de vn.saleGroup + */ + + REPLACE vn.saleTracking(saleFk, isChecked, workerFk, actionFk, stateFk) + SELECT sgd.saleFk, TRUE, account.myUser_getId(), a.accion_id id, s.id + FROM vn.saleGroupDetail sgd + JOIN vncontrol.accion a ON a.accion = 'SACAR' + JOIN vn.state s ON s.code = 'PREPARED' + WHERE sgd.saleGroupFk = vSaleGroupFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63752,31 +63756,31 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_addPrevOK`(vSectorCollectionFk INT) -BEGIN - - /** - * Inserta los registros de la colección de sector con el estado PREVIA OK - * - * @param vSectorCollectionFk Identificador de vn.sectorCollection - */ - - REPLACE vn.saleTracking(saleFk, - isChecked, - workerFk, - actionFk, - stateFk) - SELECT sgd.saleFk, - TRUE, - sc.userFk, - a.accion_id, - s.id - FROM vn.sectorCollection sc - JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk - JOIN vn.state s ON s.code = 'OK PREVIOUS' - JOIN vncontrol.accion a ON a.accion = 'PRESACAR' - WHERE sc.id = vSectorCollectionFk; - +BEGIN + + /** + * Inserta los registros de la colección de sector con el estado PREVIA OK + * + * @param vSectorCollectionFk Identificador de vn.sectorCollection + */ + + REPLACE vn.saleTracking(saleFk, + isChecked, + workerFk, + actionFk, + stateFk) + SELECT sgd.saleFk, + TRUE, + sc.userFk, + a.accion_id, + s.id + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + JOIN vn.state s ON s.code = 'OK PREVIOUS' + JOIN vncontrol.accion a ON a.accion = 'PRESACAR' + WHERE sc.id = vSectorCollectionFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63802,9 +63806,9 @@ BEGIN DELETE st.* FROM vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk - WHERE st.saleFk = vSaleFk + WHERE st.saleFk = vSaleFk AND s.code = vState COLLATE utf8_unicode_ci; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63821,20 +63825,20 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( vSaleFK INT, - vIsChecked BOOLEAN, - vOriginalQuantity INT, - vWorkerFk INT, - vAction VARCHAR(50), +CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( vSaleFK INT, + vIsChecked BOOLEAN, + vOriginalQuantity INT, + vWorkerFk INT, + vAction VARCHAR(50), vState VARCHAR(50)) BEGIN - REPLACE vn.saleTracking(saleFk, - isChecked, - originalQuantity, - workerFk, - actionFk, - stateFk) + REPLACE vn.saleTracking(saleFk, + isChecked, + originalQuantity, + workerFk, + actionFk, + stateFk) SELECT vSaleFk, vIsChecked, vOriginalQuantity, @@ -63864,7 +63868,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_Replace`(vSaleFk INT, vIsChecked INT, vOriginalQuantity INT, vStateFk INT) BEGIN - REPLACE vn.saleTracking(saleFk, isChecked, originalQuantity, stateFk) + REPLACE vn.saleTracking(saleFk, isChecked, originalQuantity, stateFk) VALUES(vSaleFk, vIsChecked, vOriginalQuantity, vStateFk); END ;; DELIMITER ; @@ -63884,26 +63888,26 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_updateIsChecked`(vSaleFk INT, vIsChecked BOOL) BEGIN - + /** * Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving * si procede, en el caso de las preparaciones previas, por usuario - * + * * @param vSaleFk Identificador de vn.sale * @param vIsChecked Estado del registro */ - + UPDATE vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION' SET st.isChecked = vIsChecked WHERE st.saleFk = vSaleFk AND st.workerFk = account.myUser_getId(); - + IF vIsChecked = FALSE THEN - - DELETE FROM vn.itemShelvingSale + + DELETE FROM vn.itemShelvingSale WHERE saleFk = vSaleFk; - + END IF; END ;; @@ -63929,15 +63933,15 @@ proc: BEGIN * * @param vSale Id de la venta * @param vOption indica en que componente pone el descuadre, NULL en casos habituales - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales; CREATE TEMPORARY TABLE tmp.recalculateSales SELECT s.id FROM sale s WHERE s.id = vSale; - + CALL vn.sale_recalcComponent(vOption); - + DROP TEMPORARY TABLE tmp.recalculateSales; END ;; DELIMITER ; @@ -63984,7 +63988,7 @@ BEGIN GROUP BY s.id; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.coste; @@ -63992,7 +63996,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.coste (PRIMARY KEY (id)) ENGINE = MEMORY SELECT s.id - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType tp ON tp.id = i.typeFk JOIN itemCategory ic ON ic.id = tp.categoryFk @@ -64011,17 +64015,17 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + SELECT ticketFk, concept INTO vTicketFk, vConcept FROM sale WHERE id = vSaleFk; - + CALL sale_calculateComponent(vSaleFk, 1); END LOOP; CLOSE vCur; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64039,115 +64043,115 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getFromTicketOrCollection`(vParam INT) -BEGIN -/** - * Visualizar lineas de la tabla sale a través del parámetro vParam que puede - * ser ticket o collection. - * - * @param vParam Identificador de ticket o collection - */ - DECLARE vIsCollection BOOL; - - SELECT COUNT(*) INTO vIsCollection - FROM collection c - WHERE c.id = vParam; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - DROP TEMPORARY TABLE IF EXISTS tmp.ticket2; - - IF vIsCollection THEN - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (id)) - ENGINE = MEMORY - SELECT tc.ticketFk id - FROM ticketCollection tc - JOIN ticket t ON t.id = tc.ticketFk - WHERE tc.collectionFk = vParam; - - CREATE TEMPORARY TABLE tmp.ticket2 - (INDEX (id)) - ENGINE = MEMORY - SELECT tc.ticketFk id - FROM ticketCollection tc - JOIN ticket t ON t.id = tc.ticketFk - WHERE tc.collectionFk = vParam; - ELSE - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (id)) - ENGINE = MEMORY - SELECT vParam id; - - CREATE TEMPORARY TABLE tmp.ticket2 - (INDEX (id)) - ENGINE = MEMORY - SELECT vParam id; - END IF; - - SELECT s.ticketFk, - sgd.saleGroupFk, - s.id as saleFk, - s.itemFk, - s.quantity, - i.longName, - i.size, - s.reserved, - MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) as isPreviousPrepared, - MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) as isPrepared, - MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) as isControlled, - MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) as isPreControlled, - ic.color, - ip.productor, - s.discount, - s.price, - i.stems, - i.category, - o.code origin, - tt.clientFk, - s.originalQuantity, - TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', - RPAD(IFNULL(i.size,''),5,' '))) line1, - '' cel1, - TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, - IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), - CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), - CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, - TRIM(CONCAT(ic.color)) line3, - p.code cel3, - s.isAdded, - sub2.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk - IFNULL(c.workerFk,getUser()) as workerFk, - IFNULL(SUM(iss.quantity),0) as pickedQuantity, - i.packingShelve, - MIN(iss.created) picked - FROM tmp.ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN ticket tt ON tt.id = t.id - LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - JOIN item i ON i.id = s.itemFk - LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id - LEFT JOIN collection c ON c.id = tc.collectionFk - LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity - FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity - FROM tmp.ticket2 t - JOIN sale s ON s.ticketFk = t.id - JOIN saleTracking st ON st.saleFk = s.id - ORDER BY st.id DESC - LIMIT 10000000000000000000) sub - GROUP BY sub.saleFk, sub.stateFK) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1 - LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id - LEFT JOIN state st ON st.id = sub2.stateFk - LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk - LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id - LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - LEFT JOIN parking p ON p.id = sg.parkingFk - GROUP BY s.id; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticket2; +BEGIN +/** + * Visualizar lineas de la tabla sale a través del parámetro vParam que puede + * ser ticket o collection. + * + * @param vParam Identificador de ticket o collection + */ + DECLARE vIsCollection BOOL; + + SELECT COUNT(*) INTO vIsCollection + FROM collection c + WHERE c.id = vParam; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + DROP TEMPORARY TABLE IF EXISTS tmp.ticket2; + + IF vIsCollection THEN + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (id)) + ENGINE = MEMORY + SELECT tc.ticketFk id + FROM ticketCollection tc + JOIN ticket t ON t.id = tc.ticketFk + WHERE tc.collectionFk = vParam; + + CREATE TEMPORARY TABLE tmp.ticket2 + (INDEX (id)) + ENGINE = MEMORY + SELECT tc.ticketFk id + FROM ticketCollection tc + JOIN ticket t ON t.id = tc.ticketFk + WHERE tc.collectionFk = vParam; + ELSE + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (id)) + ENGINE = MEMORY + SELECT vParam id; + + CREATE TEMPORARY TABLE tmp.ticket2 + (INDEX (id)) + ENGINE = MEMORY + SELECT vParam id; + END IF; + + SELECT s.ticketFk, + sgd.saleGroupFk, + s.id as saleFk, + s.itemFk, + s.quantity, + i.longName, + i.size, + s.reserved, + MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) as isPreviousPrepared, + MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) as isPrepared, + MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) as isControlled, + MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) as isPreControlled, + ic.color, + ip.productor, + s.discount, + s.price, + i.stems, + i.category, + o.code origin, + tt.clientFk, + s.originalQuantity, + TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', + RPAD(IFNULL(i.size,''),5,' '))) line1, + '' cel1, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, + IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), + CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), + CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, + TRIM(CONCAT(ic.color)) line3, + p.code cel3, + s.isAdded, + sub2.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk + IFNULL(c.workerFk,getUser()) as workerFk, + IFNULL(SUM(iss.quantity),0) as pickedQuantity, + i.packingShelve, + MIN(iss.created) picked + FROM tmp.ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN ticket tt ON tt.id = t.id + LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + JOIN item i ON i.id = s.itemFk + LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id + LEFT JOIN collection c ON c.id = tc.collectionFk + LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity + FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity + FROM tmp.ticket2 t + JOIN sale s ON s.ticketFk = t.id + JOIN saleTracking st ON st.saleFk = s.id + ORDER BY st.id DESC + LIMIT 10000000000000000000) sub + GROUP BY sub.saleFk, sub.stateFK) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1 + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN state st ON st.id = sub2.stateFk + LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk + LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + LEFT JOIN parking p ON p.id = sg.parkingFk + GROUP BY s.id; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticket2; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64191,10 +64195,10 @@ BEGIN DELETE tt.* FROM tmp.sale_getProblems tt JOIN vn.ticketObservation tto ON tto.ticketFk = tt.ticketFk - JOIN vn.observationType ot ON ot.id = tto.observationTypeFk - WHERE ot.code = 'administrative' + JOIN vn.observationType ot ON ot.id = tto.observationTypeFk + WHERE ot.code = 'administrative' AND tto.description = 'Miriam'; - + DROP TEMPORARY TABLE IF EXISTS tmp.sale_problems; CREATE TEMPORARY TABLE tmp.sale_problems ( ticketFk INT(11), @@ -64225,7 +64229,7 @@ BEGIN -- Too Little INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) - SELECT tp.ticketFk, TRUE + SELECT tp.ticketFk, TRUE FROM tmp.sale_getProblems tp JOIN vn.ticket t ON t.id = tp.ticketFk JOIN (SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat @@ -64308,25 +64312,25 @@ BEGIN -- Disponible: no va a haber suficiente producto para preparar todos los pedidos CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate); - - -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida + + -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT tl.ticketFk, - LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, + SELECT tl.ticketFk, + LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, s.id AS saleFk FROM tmp.ticket_list tl JOIN vn.ticket t ON t.id = tl.ticketFk JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -64339,7 +64343,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk; - + -- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk) SELECT ticketFk, problem, saleFk @@ -64352,7 +64356,7 @@ BEGIN JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -64365,7 +64369,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; - + -- Retraso: Disponible suficiente, pero no visible ni ubicado INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) SELECT ticketFk, problem, saleFk @@ -64379,7 +64383,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -64396,7 +64400,7 @@ BEGIN END WHILE; CLOSE vCursor; - + INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) SELECT DISTINCT tl.ticketFk, FALSE FROM tmp.ticket_list tl @@ -64426,16 +64430,16 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1)) BEGIN /** - * Calcula los problemas de cada venta + * Calcula los problemas de cada venta * para un conjunto de tickets. * * @return Problems result */ DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; - CREATE TEMPORARY TABLE tmp.sale_getProblems + CREATE TEMPORARY TABLE tmp.sale_getProblems (INDEX (ticketFk)) ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped + SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped FROM ticket t WHERE t.id = vTicketFk; @@ -64463,24 +64467,24 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT) -BEGIN - - DELETE sc.* - FROM vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk - WHERE s.ticketFk = vTicketFk - AND ct.`type` = 'otros'; - - UPDATE vn.sale s - JOIN ( - SELECT sc.saleFk, sum(sc.value ) price - FROM vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - WHERE s.ticketFk = vTicketFk - GROUP BY sc.saleFk) sub ON sub.saleFk = s.id - SET s.price = sub.price; +BEGIN + + DELETE sc.* + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk + WHERE s.ticketFk = vTicketFk + AND ct.`type` = 'otros'; + + UPDATE vn.sale s + JOIN ( + SELECT sc.saleFk, sum(sc.value ) price + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vTicketFk + GROUP BY sc.saleFk) sub ON sub.saleFk = s.id + SET s.price = sub.price; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64499,56 +64503,56 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption INT) proc: BEGIN -/** +/** * Actualiza los componentes * * @table tmp.recalculateSales - */ - DECLARE vShipped DATE; + */ + DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vTicketFk BIGINT; DECLARE vItemFk BIGINT; - DECLARE vLanded DATE; + DECLARE vLanded DATE; DECLARE vIsEditable BOOLEAN; DECLARE vZoneFk INTEGER; - + DECLARE vSale INTEGER; DECLARE vDone BOOL DEFAULT FALSE; - + DECLARE vCur CURSOR FOR SELECT id from tmp.recalculateSales; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + OPEN vCur; l: LOOP SET vDone = FALSE; - FETCH vCur INTO vSale; - + FETCH vCur INTO vSale; + IF vDone THEN LEAVE l; END IF; - - SELECT t.refFk IS NULL, - s.ticketFk, - s.itemFk , - t.zoneFk, - t.warehouseFk, - t.shipped, - t.addressFk, - t.agencyModeFk, + + SELECT t.refFk IS NULL, + s.ticketFk, + s.itemFk , + t.zoneFk, + t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, t.landed - INTO vIsEditable, - vTicketFk, - vItemFk, - vZoneFk, - vWarehouseFk, - vShipped, - vAddressFk, - vAgencyModeFk, + INTO vIsEditable, + vTicketFk, + vItemFk, + vZoneFk, + vWarehouseFk, + vShipped, + vAddressFk, + vAgencyModeFk, vLanded FROM ticket t JOIN sale s ON s.ticketFk = t.id @@ -64556,59 +64560,59 @@ proc: BEGIN WHERE s.id = vSale; CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN CALL util.throw('There is no zone for these parameters'); END IF; - + IF vLanded IS NULL OR vZoneFk IS NULL THEN - + UPDATE ticket t - SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) WHERE t.id = vTicketFk AND t.landed IS NULL; - + IF vZoneFk IS NULL THEN SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; UPDATE ticket t SET t.zoneFk = vZoneFk WHERE t.id = vTicketFk AND t.zoneFk IS NULL; END IF; - + END IF; - + DROP TEMPORARY TABLE tmp.zoneGetLanded; - - -- rellena la tabla buyUltimate con la ultima compra - CALL buyUltimate (vWarehouseFk, vShipped); - + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); + DELETE FROM tmp.buyUltimate WHERE itemFk != vItemFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot + CREATE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouseFk warehouseFk, NULL available, vItemFk itemFk, buyFk, vZoneFk zoneFk FROM tmp.buyUltimate WHERE itemFk = vItemFk; - - CALL catalog_componentPrepare(); + + CALL catalog_componentPrepare(); CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - + DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT vSale saleFk,vWarehouseFk warehouseFk; - + IF vOption IS NULL THEN SET vOption = IF(vIsEditable, 1, 6); END IF; - - CALL ticketComponentUpdateSale(vOption); + + CALL ticketComponentUpdateSale(vOption); CALL catalog_componentPurge(); - + DROP TEMPORARY TABLE tmp.buyUltimate; DROP TEMPORARY TABLE tmp.sale; - + END LOOP; - CLOSE vCur; + CLOSE vCur; END ;; DELIMITER ; @@ -64627,31 +64631,31 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_setQuantity`(vSaleFk INT, vQuantity INT) -BEGIN -/* - * Actualiza la cantidad de la línea de venta - * - * @vSaleFk id de la línea de venta - * @vQuantity cantidad a modificar - * - */ - - DECLARE vDescription VARCHAR(100); - DECLARE vOrigin INT; - - SELECT CONCAT("Cambio cantidad ",concept," de ", quantity," a ", vQuantity) INTO vDescription - FROM sale - WHERE id = vSaleFk; - - SELECT ticketFk INTO vOrigin FROM sale WHERE id = vSaleFk; - - CALL logAdd(vOrigin, 'update', 'ticket', vDescription); - - UPDATE sale - SET originalQuantity = quantity, - quantity = vQuantity - WHERE id = vSaleFk; - +BEGIN +/* + * Actualiza la cantidad de la línea de venta + * + * @vSaleFk id de la línea de venta + * @vQuantity cantidad a modificar + * + */ + + DECLARE vDescription VARCHAR(100); + DECLARE vOrigin INT; + + SELECT CONCAT("Cambio cantidad ",concept," de ", quantity," a ", vQuantity) INTO vDescription + FROM sale + WHERE id = vSaleFk; + + SELECT ticketFk INTO vOrigin FROM sale WHERE id = vSaleFk; + + CALL logAdd(vOrigin, 'update', 'ticket', vDescription); + + UPDATE sale + SET originalQuantity = quantity, + quantity = vQuantity + WHERE id = vSaleFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64694,25 +64698,25 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT) BEGIN - + /** - * Inserta un nuevo registro en vn.sectorCollectionSaleGroup + * Inserta un nuevo registro en vn.sectorCollectionSaleGroup * Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking - * + * * @param vSaleGroupFk Identificador de vn.saleGroup * @param vSectorCollectionFk Identificador de vn.sectorCollection */ - + REPLACE vn.sectorCollectionSaleGroup(sectorCollectionFk, saleGroupFk) VALUES(vSectorCollectionFk, vSaleGroupFk); - + UPDATE vn.saleGroup sg JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk - SET sg.userFk = sc.userFk + SET sg.userFk = sc.userFk WHERE sg.id = vSaleGroupFk; - - + + INSERT IGNORE vn.saleTracking(saleFk, isChecked, workerFk, @@ -64724,17 +64728,17 @@ BEGIN a.accion_id, s.id FROM vn.saleGroupDetail sgd - JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk + JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk JOIN vncontrol.accion a ON a.accion = 'SACAR' JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION' WHERE sgd.saleGroupFk = vSaleGroupFk; - + UPDATE vn.saleTracking st - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = st.saleFk + JOIN vn.saleGroupDetail sgd ON sgd.saleFk = st.saleFk SET st.isChecked = TRUE WHERE sgd.saleGroupFk = vSaleGroupFk AND st.workerFk = 20; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64752,27 +64756,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_get`(vSectorFk INT) -BEGIN - - /** - * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas - * - * @param vSectorFk Identificador de vn.sector - */ - - SELECT DISTINCT sc.id collectionFk, sc.created - FROM vn.sectorCollection sc - JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION' - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk +BEGIN + + /** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + * @param vSectorFk Identificador de vn.sector + */ + + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION' + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk LEFT JOIN vn.saleTracking st ON st.saleFk = sgd.saleFk AND st.stateFk = s.id AND st.workerFk = sc.userFk - LEFT JOIN vn.sale sl ON sl.id = st.saleFk - WHERE sc.userFk = account.myUser_getId() - AND (ISNULL(scsg.sectorCollectionFk) - OR + LEFT JOIN vn.sale sl ON sl.id = st.saleFk + WHERE sc.userFk = account.myUser_getId() + AND (ISNULL(scsg.sectorCollectionFk) + OR (NOT st.isChecked AND sl.quantity > 0)) - AND sc.created > util.VN_CURDATE(); - + AND sc.created > util.VN_CURDATE(); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64834,30 +64838,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64993,7 +64997,7 @@ BEGIN SELECT s.warehouseFk FROM vn.sector s WHERE s.id = vSectorFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65088,10 +65092,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingChange`(IN `vShelvingO` VAR BEGIN UPDATE vn.itemShelving - SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci - WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; - - + SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65110,16 +65114,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingLog_get`(shelvingFk VARCHAR(10)) BEGIN - + /* Lista el log de un carro - * + * * @param shelvingFk matrícula del carro - * + * */ - + SELECT originFk, name, creationDate, description FROM shelvingLog sl - JOIN account.user u ON u.id = sl.userFk + JOIN account.user u ON u.id = sl.userFk WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci ORDER BY creationDate DESC; @@ -65142,22 +65146,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) BEGIN - -SELECT s.itemFk, + +SELECT s.itemFk, s.concept, - CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, - CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado + CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, + CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado FROM vn.sale s LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.ticket t ON t.id = s.ticketFk LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) + WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) AND iss.saleFk IS NULL AND t.warehouseFk = vWarehouseFk GROUP BY s.itemFk HAVING sinServir > aparcado; - + END ;; DELIMITER ; @@ -65202,12 +65206,12 @@ BEGIN DELETE FROM vn.shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - + DELETE FROM vn.itemShelving WHERE visible <= 0 AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - DELETE ish.* + DELETE ish.* FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk WHERE sh.parkingFk IS NULL @@ -65215,12 +65219,12 @@ BEGIN UPDATE vn.shelving sh LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` - SET isPrinted = 0, + SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL - AND sh.isRecyclable - AND ( sh.parked IS NULL - OR + AND sh.isRecyclable + AND ( sh.parked IS NULL + OR sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) ); @@ -65241,88 +65245,88 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_getSpam`(vDated DATE, vWarehouseFk INT) -BEGIN - - /** - * Devuelve las matrículas con productos que no son necesarios para la venta hasta la fecha señalada - * - * @param vDated Fecha hasta la que se puede pasar sin esos productos. - * @param vWarehouse Identificador único de vn.warehouse - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.stock; - - CALL cache.stock_refresh(FALSE); - - CREATE TEMPORARY TABLE tmp.stock - SELECT i.id itemFk, - v.amount - IFNULL(fue.reserva,0) as visible, - fue.reserva, - sale.venta, - IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.reserva,0) as saldo - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN ( - SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva - FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk - WHERE s.code = 'FUENTES_PICASSE' - OR sh.isSpam - GROUP BY ish.itemFk - ) fue ON fue.itemFk = i.id - LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk - LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta - FROM vn2008.item_out - WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) - AND warehouse_id = vWarehouseFk - GROUP BY item_id - ) sale ON sale.item_id = i.id - LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra - FROM vn2008.item_entry_in - WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) - AND warehouse_id = vWarehouseFk - AND isVirtualStock = FALSE - GROUP BY item_id - ) buy ON buy.item_id = i.id - LEFT JOIN ( - SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado - FROM vn2008.item_entry_out - WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) - AND warehouse_id = vWarehouseFk - GROUP BY item_id - ) mov ON mov.item_id = i.id - WHERE v.amount; - - SELECT ish.shelvingFk matricula, - i.longName articulo, - ish.visible, - count(*) lineas, - sum(ish.visible <= s.saldo) spam, - p.code parking, - s.description sector , - w.name AS almacen, - sh.isSpam - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk - JOIN vn.warehouse w ON w.id = s.warehouseFk - LEFT JOIN tmp.stock s ON s.itemFk = ish.itemFk - WHERE (w.name = 'Algemesi' - OR (w.name = 'NuncaJamas' AND ish.created < util.VN_CURDATE())) - AND ish.visible - GROUP BY ish.shelvingFk - HAVING lineas = spam OR isSpam; - - DROP TEMPORARY TABLE tmp.stock; - +BEGIN + + /** + * Devuelve las matrículas con productos que no son necesarios para la venta hasta la fecha señalada + * + * @param vDated Fecha hasta la que se puede pasar sin esos productos. + * @param vWarehouse Identificador único de vn.warehouse + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.stock; + + CALL cache.stock_refresh(FALSE); + + CREATE TEMPORARY TABLE tmp.stock + SELECT i.id itemFk, + v.amount - IFNULL(fue.reserva,0) as visible, + fue.reserva, + sale.venta, + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, + IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.reserva,0) as saldo + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN ( + SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE s.code = 'FUENTES_PICASSE' + OR sh.isSpam + GROUP BY ish.itemFk + ) fue ON fue.itemFk = i.id + LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta + FROM vn2008.item_out + WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) + AND warehouse_id = vWarehouseFk + GROUP BY item_id + ) sale ON sale.item_id = i.id + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra + FROM vn2008.item_entry_in + WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) + AND warehouse_id = vWarehouseFk + AND isVirtualStock = FALSE + GROUP BY item_id + ) buy ON buy.item_id = i.id + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado + FROM vn2008.item_entry_out + WHERE dat BETWEEN util.VN_CURDATE() AND util.dayend(vDated) + AND warehouse_id = vWarehouseFk + GROUP BY item_id + ) mov ON mov.item_id = i.id + WHERE v.amount; + + SELECT ish.shelvingFk matricula, + i.longName articulo, + ish.visible, + count(*) lineas, + sum(ish.visible <= s.saldo) spam, + p.code parking, + s.description sector , + w.name AS almacen, + sh.isSpam + FROM vn.itemShelving ish + JOIN vn.item i ON i.id = ish.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.warehouse w ON w.id = s.warehouseFk + LEFT JOIN tmp.stock s ON s.itemFk = ish.itemFk + WHERE (w.name = 'Algemesi' + OR (w.name = 'NuncaJamas' AND ish.created < util.VN_CURDATE())) + AND ish.visible + GROUP BY ish.shelvingFk + HAVING lineas = spam OR isSpam; + + DROP TEMPORARY TABLE tmp.stock; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65397,20 +65401,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `solunionRiskRequest`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY - SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc + SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification WHERE dateEnd IS NULL ORDER BY ci.creationDate DESC LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente; - + CALL vn2008.risk_vs_client_list(util.VN_CURDATE()); - - SELECT + + SELECT c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo, cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo, f.Consumo consumo_anual, c.Vencimiento, ci.grade @@ -65420,7 +65424,7 @@ BEGIN JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente GROUP BY Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -65493,15 +65497,15 @@ BEGIN */ CALL vn.stockTraslation(vDated); - DELETE - FROM vn.stockBuyed + DELETE + FROM vn.stockBuyed WHERE `date` = vDated; INSERT INTO vn.stockBuyed(`user`, buyed, `date`, description) - SELECT it.workerFk, - SUM(( ti.amount / b.packing ) * vn.buy_getVolume(b.id)) / vc.palletM3 / 1000000 buyed, + SELECT it.workerFk, + SUM(( ti.amount / b.packing ) * vn.buy_getVolume(b.id)) / vc.palletM3 / 1000000 buyed, vDated, - u.name + u.name FROM tmp_item ti JOIN vn.item i ON i.id = ti.item_id JOIN vn.itemType it ON it.id = i.typeFk @@ -65513,18 +65517,18 @@ BEGIN JOIN account.`user` u ON u.id = it.workerFk WHERE ic.display != 0 GROUP BY it.workerFk; - + INSERT INTO stockBuyed(buyed, `date`, description) SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), vDated, IF(c.country = 'España',p.name,c.country) destiny FROM vn.itemTicketOut ito - JOIN vn.ticket t ON t.id = ito.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.ticket t ON t.id = ito.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk JOIN vn.country c ON c.id = p.countryFk JOIN vn.warehouse wh ON wh.id = t.warehouseFk JOIN vn.itemCost ic ON ic.itemFk = ito.itemFk AND ic.warehouseFk = t.warehouseFk JOIN vn.volumeConfig vc - WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated) + WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated) AND wh.code = 'VNH' GROUP BY destiny; @@ -65563,21 +65567,21 @@ BEGIN CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY - SELECT item_id, SUM(amount) amount + SELECT item_id, SUM(amount) amount FROM vn2008.item_entry_in - WHERE dat = vDate - AND vDate >= util.VN_CURDATE() + WHERE dat = vDate + AND vDate >= util.VN_CURDATE() AND warehouse_id = vWarehouse AND isVirtualStock is FALSE - GROUP BY item_id + GROUP BY item_id HAVING amount != 0; CALL `cache`.stock_refresh (FALSE); INSERT INTO tmp_item (item_id,amount) - SELECT item_id,s.amount + SELECT item_id,s.amount FROM `cache`.stock s - WHERE warehouse_id = vWarehouse + WHERE warehouse_id = vWarehouse ON DUPLICATE KEY UPDATE amount = tmp_item.amount + VALUES(amount); CALL buyUltimate(vWarehouse,vDate); @@ -65605,10 +65609,10 @@ BEGIN DECLARE vBossId INT; DECLARE vDone BOOL; DECLARE workerCur CURSOR FOR - SELECT workerFk - FROM tmp.subordinate + SELECT workerFk + FROM tmp.subordinate WHERE NOT isChecked; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR 1062 BEGIN @@ -65616,29 +65620,29 @@ BEGIN END; DROP TEMPORARY TABLE IF EXISTS tmp.subordinate; - + CREATE TEMPORARY TABLE tmp.subordinate (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBossFk AS workerFk, 0 AS isChecked; - + WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO OPEN workerCur; workerLoop: LOOP SET vDone = FALSE; FETCH workerCur INTO vBossId; - + IF vDone THEN LEAVE workerLoop; END IF; - - INSERT INTO tmp.subordinate - SELECT id, 0 - FROM worker + + INSERT INTO tmp.subordinate + SELECT id, 0 + FROM worker WHERE bossFk = vBossId; - - UPDATE tmp.subordinate + + UPDATE tmp.subordinate SET isChecked = 1 WHERE workerFk = vBossId; END LOOP; @@ -65678,13 +65682,13 @@ BEGIN -- Calcula el balance inicial y final de cada proveedor INSERT INTO openingBalance SELECT MAX(dueDated), - supplierFk, - companyFk, + supplierFk, + companyFk, sum(amount) eurAmount, sum(divisa) foreignAmount FROM ( SELECT p.dueDated, - p.supplierFk, + p.supplierFk, p.companyFk, p.amount, p.divisa @@ -65700,7 +65704,7 @@ BEGIN SELECT iidd.dueDated, ii.supplierFk, ii.companyFk, - - iidd.amount, + - iidd.amount, - iidd.foreignValue FROM invoiceIn ii JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk @@ -65708,14 +65712,14 @@ BEGIN JOIN company co ON co.id = ii.companyFk WHERE iidd.dueDated > '2014-12-31' AND iidd.dueDated <= vEnded - AND ii.isBooked AND co.`code` = 'VNL' + AND ii.isBooked AND co.`code` = 'VNL' AND c.`code` <> 'EUR' UNION ALL SELECT se.dueDated, se.supplierFk, se.companyFk, - - se.amount, + - se.amount, 0 FROM supplierExpense se JOIN currency c ON c.id = se.currencyFk @@ -65725,7 +65729,7 @@ BEGIN AND co.`code` = 'VNL' AND c.`code` <> 'EUR' ) sub GROUP BY companyFk, supplierFk; - + SELECT ob.dueDated , ob.supplierFk , ob.companyFk @@ -65812,7 +65816,7 @@ BEGIN SELECT MAX(`row`) INTO vMaxRow FROM tmp.supplierPackagingList; - + DROP TEMPORARY TABLE IF EXISTS tmp.supplierPackaging; CREATE TEMPORARY TABLE tmp.supplierPackaging( supplierFk INT, @@ -65826,7 +65830,7 @@ BEGIN warehouse INT, buyingValue INT, balance INT); - + l1: LOOP IF vCounter = vMaxRow THEN @@ -65835,12 +65839,12 @@ BEGIN SET vCounter = vCounter + 1; SET @vBalance = 0; END IF; - + SELECT itemFk INTO vItemFk FROM tmp.supplierPackagingList WHERE `row` = vCounter; - + INSERT INTO tmp.supplierPackaging SELECT supplierFk, itemFk, @@ -65868,9 +65872,9 @@ BEGIN WHERE supplierFk = vSupplierFk AND landed >= vFromDated AND itemFk = vItemFk - + UNION ALL - + SELECT vSupplierFk, itemFk, longName, @@ -65950,7 +65954,7 @@ BEGIN - SUM(iid.amount) mysql, 0 sage FROM invoiceInDueDay iid - JOIN invoiceIn ii ON ii.id = iid.invoiceInFk + JOIN invoiceIn ii ON ii.id = iid.invoiceInFk WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo AND ii.isBooked GROUP BY ii.id @@ -66089,15 +66093,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketBoxesView`(IN vTicketFk INT) BEGIN - - SELECT s.id, - s.itemFk, - s.concept, - floor(s.quantity / b.packing) as Cajas, - b.packing, - s.isPicked, + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, i.size - FROM ticket t + FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk @@ -66108,7 +66112,7 @@ BEGIN AND p.isBox GROUP BY s.itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66130,7 +66134,7 @@ BEGIN DECLARE vDateStart DATETIME DEFAULT DATE(vDate); DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime; CREATE TEMPORARY TABLE tmp.ticketBuiltTime @@ -66143,7 +66147,7 @@ BEGIN SELECT ticketFk, builtTime FROM ( - SELECT + SELECT Id_Ticket as ticketFk, odbc_date as builtTime FROM @@ -66151,13 +66155,13 @@ BEGIN WHERE odbc_date BETWEEN vDateStart AND vDateEnd ORDER BY Id_Ticket, odbc_date DESC LIMIT 10000000000000000000 - ) sub + ) sub GROUP BY ticketFk ) sub2 ON sub2.ticketFk = t.id WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate) AND t.clientFk NOT IN (50,400,200) AND t.companyFk = 442 - + ; END ;; @@ -66194,10 +66198,10 @@ BEGIN DECLARE vZoneFk INT; REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket + 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 agencyMode a @@ -66207,47 +66211,47 @@ BEGIN IF vLanded IS NULL THEN CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse, TRUE); UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk SET t.landed = zgl.landed, t.zoneFk = 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); + CALL buyUltimate(vWarehouse, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot + CREATE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - - CALL catalog_componentPrepare(); + + CALL catalog_componentPrepare(); CALL catalog_componentCalculate(vZoneFk, vAddress, vShipped, vWarehouse); -- 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 + 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 + 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 @@ -66255,11 +66259,11 @@ BEGIN -- Limpieza CALL catalog_componentPurge(); - DROP TEMPORARY TABLE IF EXISTS - tmp.buyUltimate, - tmp.sale, + DROP TEMPORARY TABLE IF EXISTS + tmp.buyUltimate, + tmp.sale, tmp.zoneGetLanded; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66282,12 +66286,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateFromType`( vLanded D vTypeFk INT) BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - (INDEX (itemFk)) - ENGINE = MEMORY + CREATE TEMPORARY TABLE tmp.item + (INDEX (itemFk)) + ENGINE = MEMORY SELECT id itemFk FROM vn.item WHERE typeFk = vTypeFk; - + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.ticketLot; @@ -66309,7 +66313,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculatePurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketCalculateItem, tmp.ticketComponentPrice, tmp.ticketComponent, @@ -66333,56 +66337,56 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon`(vTicketFk INT, vNewShipped DATE) BEGIN - + DECLARE done INT DEFAULT FALSE; - DECLARE vNewTicketFk INT; + DECLARE vNewTicketFk INT; DECLARE vOldSaleFk INT; DECLARE vNewSaleFk INT; - + DECLARE cur1 CURSOR FOR SELECT id FROM vn.sale WHERE ticketFk = vTicketFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - + SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE()); - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.ticket + + UPDATE vn.ticket SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed), shipped = vNewShipped WHERE id = vNewTicketFk; - + OPEN cur1; - + read_loop: LOOP - + FETCH cur1 INTO vOldSaleFk; - + IF done THEN LEAVE read_loop; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed) SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed FROM vn.sale WHERE id = vOldSaleFk; - + SELECT max(id) INTO vNewSaleFk FROM vn.sale WHERE ticketFk = vNewTicketFk; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value, isGreuge) SELECT vNewSaleFk, componentFk, value, isGreuge FROM vn.saleComponent WHERE saleFk = vOldSaleFk; - + END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66404,18 +66408,18 @@ BEGIN DECLARE vShipped DATE; DECLARE vMaxDated DATE; - - SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) + + SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) INTO vShipped, vMaxDated FROM vn.ticket WHERE id = vTicketFk; - + WHILE vShipped <= vMaxDated DO - + SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped); - + CALL vn.ticketClon(vTicketFk, vShipped); - + END WHILE; END ;; @@ -66437,10 +66441,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_get`(vTicketFk INT) BEGIN - SELECT tc.collectionFk + SELECT tc.collectionFk FROM vn.ticketCollection tc WHERE ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66458,19 +66462,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT) -BEGIN - - /* - * Inserta número de baldas que ocupa un ticket - * - * @param vTicketFk Identificador de ticket - * @param vUsedShelves Número de baldas - */ - - UPDATE ticketCollection tc - SET tc.usedShelves = vUsedShelves - WHERE tc.ticketFk = vTicketFk; - +BEGIN + + /* + * Inserta número de baldas que ocupa un ticket + * + * @param vTicketFk Identificador de ticket + * @param vUsedShelves Número de baldas + */ + + UPDATE ticketCollection tc + SET tc.usedShelves = vUsedShelves + WHERE tc.ticketFk = vTicketFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66508,18 +66512,18 @@ BEGIN END; START TRANSACTION; - + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.agencyModeFk = vAgencyModeFk, t.addressFk = vAddressFk, @@ -66530,12 +66534,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -66577,104 +66581,104 @@ BEGIN DECLARE vComponentFk INT; DECLARE vRenewComponents BOOLEAN; DECLARE vKeepPrices BOOLEAN; - + CASE vOption - WHEN 1 THEN + WHEN 1 THEN SET vRenewComponents = TRUE; SET vKeepPrices = FALSE; WHEN 2 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - WHEN 3 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; - SET vRenewComponents = TRUE; - SET vKeepPrices = TRUE; - WHEN 4 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + WHEN 3 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - /* WHEN 5 THEN + WHEN 4 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + /* WHEN 5 THEN SET vComponentFk = 35; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE;*/ - WHEN 6 THEN + WHEN 6 THEN SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 7 THEN REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) + SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; WHEN 8 THEN - DELETE sc.* + DELETE sc.* FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; - WHEN 9 THEN + WHEN 9 THEN SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; END CASE; IF vRenewComponents THEN - DELETE sc.* - FROM tmp.sale tmps + DELETE sc.* + FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk JOIN `component` c ON c.id = sc.componentFk WHERE c.isRenewable; - + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, tc.componentFk, tc.cost - FROM sale s + FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN `component` c ON c.id = tc.componentFk WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE); - - -- Añadir componente venta por paquete + + -- Añadir componente venta por paquete DROP TEMPORARY TABLE IF EXISTS tmp.sale2; CREATE TEMPORARY TABLE tmp.sale2 (PRIMARY KEY (saleFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM tmp.sale; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent2; CREATE TEMPORARY TABLE tmp.ticketComponent2 - SELECT * FROM tmp.ticketComponent; - - REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT * FROM tmp.ticketComponent; + + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT t.id, t.componentFk, t.cost FROM ( SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto FROM vn.sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id JOIN vn.buy b ON b.id = buy_id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' + JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' LEFT JOIN ( SELECT s.id FROM vn.sale s @@ -66685,8 +66689,8 @@ BEGIN ) tp ON tp.id = s.id WHERE tp.id IS NULL HAVING resto <> 0) t; - - DROP TEMPORARY TABLE IF EXISTS + + DROP TEMPORARY TABLE IF EXISTS tmp.sale2, tmp.ticketComponent2; END IF; @@ -66704,26 +66708,26 @@ BEGIN UPDATE sale s JOIN item i on i.id = s.itemFk JOIN itemType it on it.id = i.typeFk - JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk + JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk GROUP BY sc.saleFk) sc ON sc.saleFk = s.id SET s.price = sumValue / ((100 - s.discount) / 100) - WHERE it.code != 'PRT' ; - + WHERE it.code != 'PRT' ; + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id WHERE sc.componentFk != 21 - GROUP BY s.id + GROUP BY s.id HAVING ROUND(saleValue, 4) <> 0; END IF; - + UPDATE sale s JOIN ( - SELECT SUM(sc.value) sumValue, sc.saleFk + SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk JOIN `component` c ON c.id = sc.componentFk @@ -66737,10 +66741,10 @@ BEGIN JOIN sale s on s.id = sc.saleFk JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk - WHERE it.code = 'PRT'; - + WHERE it.code = 'PRT'; + INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 15, s.price + SELECT s.id, 15, s.price FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN item i ON i.id = s.itemFK @@ -66876,24 +66880,24 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket ENGINE = MEMORY SELECT vTicketFk ticketFk; - + CALL vn.ticket_getTax(NULL); - SELECT + SELECT tt.ticketFk, CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase, CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax, - pgc.*, + pgc.*, CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base, pgc.rate / 100 as vatPercent FROM tmp.ticketTax tt JOIN vn.pgc ON pgc.code = tt.pgcFk LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code; - + DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticketAmount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66931,29 +66935,29 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; CREATE TEMPORARY TABLE tmp.ticketTax (INDEX (ticketFk)) ENGINE = MEMORY SELECT tmpTicket.ticketFk, bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) + SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) AS taxableBase, SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) * pgc.rate / 100 AS tax, tc.code - + FROM tmp.ticket tmpTicket JOIN sale s ON s.ticketFk = tmpTicket.ticketFk JOIN item i ON i.id = s.itemFk JOIN ticket t ON t.id = tmpTicket.ticketFk JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata + JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp + JOIN bookingPlanner bp ON bp.countryFk = su.countryFk AND bp.taxAreaFk = ata.areaFk AND bp.taxClassFk = itc.taxClassFk @@ -66961,7 +66965,7 @@ BEGIN JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpTicket.ticketFk, pgc.code HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) @@ -66972,7 +66976,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67009,7 +67013,7 @@ BEGIN FROM tmp.ticket t LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk GROUP BY ticketFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; END ;; @@ -67075,25 +67079,25 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketManaToPromo`(vTicketFk INT) -BEGIN - - DECLARE vManaComponent INT; - - DECLARE vPromoComponent INT; - - SELECT id INTO vManaComponent - FROM vn.component c - WHERE c.code = 'mana'; - - SELECT id INTO vPromoComponent - FROM vn.component c - WHERE c.code = 'floramondoPromo'; - - UPDATE vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - SET componentFk = vPromoComponent - WHERE componentFk = vManaComponent - AND s.ticketFk = vTicketFk; +BEGIN + + DECLARE vManaComponent INT; + + DECLARE vPromoComponent INT; + + SELECT id INTO vManaComponent + FROM vn.component c + WHERE c.code = 'mana'; + + SELECT id INTO vPromoComponent + FROM vn.component c + WHERE c.code = 'floramondoPromo'; + + UPDATE vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + SET componentFk = vPromoComponent + WHERE componentFk = vManaComponent + AND s.ticketFk = vTicketFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67117,18 +67121,18 @@ BEGIN DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) INTO vLevel, vCollectionFk FROM vn.ticketCollection WHERE ticketFk = vTicketFk LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking WHERE ticketFk = vTicketFk; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -67155,7 +67159,7 @@ BEGIN AND sc.isPackagingArea AND tp.created < vParked AND t.packages <=> 0); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67176,7 +67180,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketNotInvoicedByClient`(vClientF BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - + CREATE TEMPORARY TABLE tmp.ticket SELECT id ticketFk FROM ticket @@ -67186,7 +67190,7 @@ BEGIN CALL vn.ticketGetTotal; - SELECT c.id, + SELECT c.id, c.name as Cliente, t.shipped as Fecha, t.id as Id_Ticket, @@ -67197,7 +67201,7 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, - tmp.ticketTotal; + tmp.ticketTotal; END ;; DELIMITER ; @@ -67216,22 +67220,22 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT) -BEGIN - - /** - * Inserta observaciones para los tickets con clientes nuevos o recuperados - * - * @param vTicketFk Identificador de vn.ticket - */ - - DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; - +BEGIN + + /** + * Inserta observaciones para los tickets con clientes nuevos o recuperados + * + * @param vTicketFk Identificador de vn.ticket + */ + + DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; + INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) SELECT vTicketFk, ot.id, vDescription FROM vn.observationType ot WHERE ot.hasNewBornMessage - ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); - + ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67249,66 +67253,66 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) -BEGIN - -/** - * Averigua los tickets que se han saltado por un error en el proceso encajado - * @param vTicketFk Ticket - * @param vItemPackingTypeFk Modo de encajado - * @return un select con los tickets afectados - */ - - DECLARE vParkingFk INT; - DECLARE vParked DATETIME; - DECLARE vLevel INT; - DECLARE vWagon INT; - DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) - INTO vLevel, vWagon, vCollectionFk - FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk - WHERE ticketFk = vTicketFk - ORDER BY c.id DESC - LIMIT 1; - - SELECT created, parkingFk - INTO vParked, vParkingFk - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk - WHERE ticketFk = vTicketFk - AND s.itemPackingTypeFk = vItemPackingTypeFk - AND s.isPackagingArea ; - - SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND ( - ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) - OR - ( tc.collectionFk = vCollectionFk - AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) - ) - ) - ) -- Etiquetas que no se han escaneado y ya estamos con una posterior - OR - (s.alertLevel > 1 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND tp.created < vParked - AND t.packages <=> 0); +BEGIN + +/** + * Averigua los tickets que se han saltado por un error en el proceso encajado + * @param vTicketFk Ticket + * @param vItemPackingTypeFk Modo de encajado + * @return un select con los tickets afectados + */ + + DECLARE vParkingFk INT; + DECLARE vParked DATETIME; + DECLARE vLevel INT; + DECLARE vWagon INT; + DECLARE vCollectionFk INT; + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + INTO vLevel, vWagon, vCollectionFk + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk + WHERE ticketFk = vTicketFk + ORDER BY c.id DESC + LIMIT 1; + + SELECT created, parkingFk + INTO vParked, vParkingFk + FROM vn.ticketParking tp + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE ticketFk = vTicketFk + AND s.itemPackingTypeFk = vItemPackingTypeFk + AND s.isPackagingArea ; + + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia + FROM vn.ticketParking tp + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk + JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.zone z ON z.id = t.zoneFk + JOIN vn.agencyMode am ON am.id = z.agencyModeFk + JOIN vn.state s ON s.id = tst.state + WHERE (s.alertLevel < 2 + AND tp.parkingFk = vParkingFk + AND sc.isPackagingArea + AND ( + ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) + OR + ( tc.collectionFk = vCollectionFk + AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + ) + ) + ) -- Etiquetas que no se han escaneado y ya estamos con una posterior + OR + (s.alertLevel > 1 + AND tp.parkingFk = vParkingFk + AND sc.isPackagingArea + AND tp.created < vParked + AND t.packages <=> 0); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67359,11 +67363,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRequest_Add`(vDescription VARCHAR(255), vQuantity INT, vPrice DOUBLE, vTicketFk INT, vBuyerCode VARCHAR(3)) BEGIN - INSERT INTO vn.ticketRequest(description, - quantity, - price, - ticketFk, - buyerCode, + INSERT INTO vn.ticketRequest(description, + quantity, + price, + ticketFk, + buyerCode, requesterFk) VALUES(vDescription, vQuantity, @@ -67371,7 +67375,7 @@ BEGIN vTicketFk, vBuyerCode, vn.getUser()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67389,29 +67393,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) -BEGIN - - /* Modifica el estado de un ticket de hoy - * - * @param vTicketFk el id del ticket - * @param vStateCode estado a modificar del ticket - * - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id - WHERE tst.ticket = vTicketFk - LIMIT 1; - - IF vAlertLevel < 2 THEN - - CALL vn.ticket_setState(vTicketFk, vStateCode); - - END IF; - +BEGIN + + /* Modifica el estado de un ticket de hoy + * + * @param vTicketFk el id del ticket + * @param vStateCode estado a modificar del ticket + * + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + WHERE tst.ticket = vTicketFk + LIMIT 1; + + IF vAlertLevel < 2 THEN + + CALL vn.ticket_setState(vTicketFk, vStateCode); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67430,25 +67434,25 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* * @deprecated:utilizar ticket_setState */ - + DECLARE vAlertLevel INT; - SELECT s.alertLevel INTO vAlertLevel + SELECT s.alertLevel INTO vAlertLevel FROM vn.state s JOIN vn.ticketState ts ON ts.stateFk = s.id WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state + FROM vn.state WHERE `code` = vStateCode collate utf8_unicode_ci; - + END IF; END ;; @@ -67551,36 +67555,36 @@ BEGIN DECLARE vCountry INT; DECLARE vTaxArea VARCHAR(15); DECLARE vSpainCountryCode INT DEFAULT 1; - - SELECT id - INTO vInvoice - FROM vn.invoiceOut + + SELECT id + INTO vInvoice + FROM vn.invoiceOut WHERE ref = vInvoiceRef; - - SELECT s.countryFk + + SELECT s.countryFk INTO vCountry FROM vn.supplier s JOIN vn.invoiceOut io ON io.companyFk = s.id WHERE io.id = vInvoice; - + SELECT IF( - c.isEqualizated - AND c.countryFk = vSpainCountryCode + c.isEqualizated + AND c.countryFk = vSpainCountryCode AND i.taxAreaFk = 'NATIONAL', 'EQU', i.taxAreaFk ) INTO vTaxArea FROM vn.invoiceOutSerial i - JOIN vn.invoiceOut io ON io.serial = i.code + JOIN vn.invoiceOut io ON io.serial = i.code JOIN vn.client c ON c.id = io.clientFk WHERE io.id = vInvoice; - + DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; CREATE TEMPORARY TABLE vn.ticketToInvoice - SELECT id - FROM vn.ticket + SELECT id + FROM vn.ticket WHERE refFk = vInvoiceRef; END ;; @@ -67749,21 +67753,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT) -BEGIN - - INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) - SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed - FROM vn.ticket t - JOIN vn.warehouse w ON w.name = 'INVENTARIO' - WHERE t.id = vOriginalTicket; - - SELECT LAST_INSERT_ID() INTO vNewTicket; - - INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount - FROM vn.sale s - WHERE s.ticketFk = vOriginalTicket; - +BEGIN + + INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) + SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed + FROM vn.ticket t + JOIN vn.warehouse w ON w.name = 'INVENTARIO' + WHERE t.id = vOriginalTicket; + + SELECT LAST_INSERT_ID() INTO vNewTicket; + + INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount + FROM vn.sale s + WHERE s.ticketFk = vOriginalTicket; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67784,7 +67788,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canAdvance`(vDated DATE, vWa BEGIN /** * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. - * + * * @param vDated Fecha de los tickets que se quieren adelantar. * @param vWarehouseFk Almacén */ @@ -67792,7 +67796,7 @@ BEGIN DECLARE vDateToAdvance DATE; SELECT inventoried INTO vDateInventory FROM vn.config; - + SET vDateToAdvance = TIMESTAMPADD(DAY,-1,vDated); DROP TEMPORARY TABLE IF EXISTS tmp.stock; @@ -67807,7 +67811,7 @@ BEGIN SELECT itemFk, quantity FROM vn.itemTicketOut WHERE shipped >= vDateInventory - AND shipped < vDated + AND shipped < vDated AND warehouseFk = vWarehouseFk UNION ALL SELECT itemFk, quantity @@ -67819,8 +67823,8 @@ BEGIN UNION ALL SELECT itemFk, quantity FROM vn.itemEntryOut - WHERE shipped >= vDateInventory - AND shipped < vDated + WHERE shipped >= vDateInventory + AND shipped < vDated AND warehouseOutFk = vWarehouseFk ) t GROUP BY itemFk HAVING amount != 0; @@ -67835,9 +67839,9 @@ BEGIN t2.ipt FROM vn.ticket t JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.state st ON st.id = ts.stateFk - LEFT JOIN (SELECT - t2.id ticketFk, + JOIN vn.state st ON st.id = ts.stateFk + LEFT JOIN (SELECT + t2.id ticketFk, t2.addressFk, st.name state, GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt @@ -67845,17 +67849,17 @@ BEGIN JOIN vn.sale s ON s.ticketFk = t2.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.ticketState ts ON ts.ticketFk = t2.id - JOIN vn.state st ON st.id = ts.stateFk + JOIN vn.state st ON st.id = ts.stateFk WHERE t2.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) AND t2.warehouseFk = vWarehouseFk GROUP BY t2.id) t2 ON t2.addressFk = t.addressFk JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN tmp.stock st ON st.itemFk = s.itemFk + LEFT JOIN tmp.stock st ON st.itemFk = s.itemFk WHERE t.shipped BETWEEN vDated AND util.dayend(vDated) AND t.warehouseFk = vWarehouseFk GROUP BY t.id; - + DROP TEMPORARY TABLE tmp.stock; END ;; DELIMITER ; @@ -67874,67 +67878,67 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canMerge`(vDated DATE, vScopeDays INT, vLitersMax INT, vLinesMax INT, vWarehouseFk INT) -BEGIN -/** - * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro - * - * @param vDated Fecha en cuestión - * @param vScopeDays Dias en el futuro a sondear - * @param vLitersMax Volumen máximo de los tickets a catapultar - * @param vLinesMax Número máximo de lineas de los tickets a catapultar - * @param vWarehouseFk Identificador de vn.warehouse - */ - SELECT sv.ticketFk, - GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, - CAST(SUM(litros) AS DECIMAL(10,0)) liters, - CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, - st.name state, - sub2.id ticketFuture, - sub2.shipped, - sub2.iptd tfIpt, - sub2.state tfState - FROM vn.saleVolume sv - JOIN vn.sale s ON s.id = sv.saleFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.ticket t ON t.id = sv.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.country c ON c.id = p.countryFk - JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.state st ON st.id = ts.stateFk - JOIN vn.alertLevel al ON al.id = ts.alertLevel - LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id - LEFT JOIN ( - SELECT * - FROM ( - SELECT t.addressFk, - t.id, - t.shipped, - st.name state, - GROUP_CONCAT(DISTINCT i.itemPackingTypeFk - ORDER BY i.itemPackingTypeFk) iptd - FROM vn.ticket t - JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.state st ON st.id = ts.stateFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.alertLevel al ON al.id = st.alertLevel - JOIN vn.item i ON i.id = s.itemFk - WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated) - AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated)) - AND t.warehouseFk = vWarehouseFk - AND al.code = 'FREE' - GROUP BY t.id - ) sub - GROUP BY sub.addressFk - ) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id - WHERE t.shipped BETWEEN vDated AND util.dayend(vDated) - AND t.warehouseFk = vWarehouseFk - AND al.code = 'FREE' - AND tp.ticketFk IS NULL - GROUP BY sv.ticketFk - HAVING liters <= vLitersMax - AND `lines` <= vLinesMax - AND ticketFuture; +BEGIN +/** + * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro + * + * @param vDated Fecha en cuestión + * @param vScopeDays Dias en el futuro a sondear + * @param vLitersMax Volumen máximo de los tickets a catapultar + * @param vLinesMax Número máximo de lineas de los tickets a catapultar + * @param vWarehouseFk Identificador de vn.warehouse + */ + SELECT sv.ticketFk, + GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, + CAST(SUM(litros) AS DECIMAL(10,0)) liters, + CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, + st.name state, + sub2.id ticketFuture, + sub2.shipped, + sub2.iptd tfIpt, + sub2.state tfState + FROM vn.saleVolume sv + JOIN vn.sale s ON s.id = sv.saleFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.ticket t ON t.id = sv.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.country c ON c.id = p.countryFk + JOIN vn.ticketState ts ON ts.ticketFk = t.id + JOIN vn.state st ON st.id = ts.stateFk + JOIN vn.alertLevel al ON al.id = ts.alertLevel + LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id + LEFT JOIN ( + SELECT * + FROM ( + SELECT t.addressFk, + t.id, + t.shipped, + st.name state, + GROUP_CONCAT(DISTINCT i.itemPackingTypeFk + ORDER BY i.itemPackingTypeFk) iptd + FROM vn.ticket t + JOIN vn.ticketState ts ON ts.ticketFk = t.id + JOIN vn.state st ON st.id = ts.stateFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.alertLevel al ON al.id = st.alertLevel + JOIN vn.item i ON i.id = s.itemFk + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated) + AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated)) + AND t.warehouseFk = vWarehouseFk + AND al.code = 'FREE' + GROUP BY t.id + ) sub + GROUP BY sub.addressFk + ) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id + WHERE t.shipped BETWEEN vDated AND util.dayend(vDated) + AND t.warehouseFk = vWarehouseFk + AND al.code = 'FREE' + AND tp.ticketFk IS NULL + GROUP BY sv.ticketFk + HAVING liters <= vLitersMax + AND `lines` <= vLinesMax + AND ticketFuture; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67991,12 +67995,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_checkFullyControlled`(vWorkerFk INT, vTicketFk INT ) BEGIN /** - * Comprueba que no hay ningún ticket pendiente de revisar de alguna colección que haya revisado el trabajador + * Comprueba que no hay ningún ticket pendiente de revisar de alguna colección que haya revisado el trabajador * @param vWorkerFk id del user * @param vTicketFk número de ticket escaneada - * + * */ - + SELECT t.id FROM ticket t JOIN sale s ON s.ticketFk = t.id @@ -68016,11 +68020,11 @@ BEGIN )sub ON sub.collectionFk = tc.collectionFk JOIN ticketState ts ON ts.ticketFk = t.id JOIN state s2 ON s2.id = ts.stateFk - WHERE s2.code IN ('ON_PREPARATION', 'PREPARED', 'PREVIOUS_PREPARATION', 'OK PREVIOUS') + WHERE s2.code IN ('ON_PREPARATION', 'PREPARED', 'PREVIOUS_PREPARATION', 'OK PREVIOUS') AND t.shipped >= util.VN_CURDATE() AND s.quantity <>0 LIMIT 1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68043,7 +68047,7 @@ BEGIN /** * Comprueba que los tickets entre un rango de fechas tienen componentes * - * @param vShippedFrom rango inicial de fecha + * @param vShippedFrom rango inicial de fecha * @param vShippedTo rango final de fecha */ DECLARE v_done BOOL DEFAULT FALSE; @@ -68062,9 +68066,9 @@ BEGIN AND clt.isActive != 0 AND ic.merchandise != 0 GROUP BY s.id; - + DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.coste; @@ -68083,7 +68087,7 @@ BEGIN JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1 WHERE t.shipped >= vShippedFrom AND ic.merchandise != 0; - + OPEN vCur; l: LOOP @@ -68097,8 +68101,8 @@ BEGIN CALL sale_calculateComponent(vSaleFk, 1); END LOOP; - CLOSE vCur; - DROP TEMPORARY TABLE tmp.coste; + CLOSE vCur; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68122,7 +68126,7 @@ BEGIN * * @param vOriginalTicket ticket Original * @param vNewTicket ticket creado - */ + */ DECLARE vStateFk INT; INSERT INTO ticket ( @@ -68139,7 +68143,7 @@ BEGIN zoneBonus, routeFk, priority, - hasPriority + hasPriority ) SELECT clientFk, @@ -68155,29 +68159,29 @@ BEGIN zoneBonus, routeFk, priority, - hasPriority + hasPriority FROM ticket WHERE id = vOriginalTicket; SET vNewTicket = LAST_INSERT_ID(); - + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) SELECT vNewTicket, ao.observationTypeFk, ao.description FROM addressObservation ao JOIN ticket t ON t.addressFk = ao.addressFk WHERE t.id = vNewTicket; - + INSERT INTO ticketLog - SET originFk = vNewTicket, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vNewTicket, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket, ' clonando el ', vOriginalTicket); - + INSERT INTO ticketLog - SET originFk = vOriginalTicket, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vOriginalTicket, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket, ' clonando el ', vOriginalTicket); INSERT INTO vncontrol.inter(Id_Ticket, state_id, Id_Trabajador, odbc_date) SELECT vNewTicket, state_id, Id_Trabajador , odbc_date - FROM vncontrol.inter + FROM vncontrol.inter WHERE Id_Ticket = vOriginalTicket ORDER BY odbc_date; END ;; @@ -68210,16 +68214,16 @@ BEGIN DECLARE vAgencyModeFk INT; DECLARE vNewTicket INT; DECLARE vYear INT; - + DECLARE rsTicket CURSOR FOR SELECT tt.ticketFk, tt.weekDay, t.clientFk, t.warehouseFk, t.companyFk, t.addressFk, tt.agencyModeFk - FROM vn.ticketWeekly tt + FROM vn.ticketWeekly tt JOIN vn.ticket t ON tt.ticketFk = t.id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; SET vYear = YEAR(util.VN_CURDATE()) + IF(vWeek < WEEK(util.VN_CURDATE()),1, 0); - + OPEN rsTicket; myLoop: LOOP BEGIN @@ -68235,7 +68239,7 @@ BEGIN LEAVE myLoop; END IF; - SELECT dated INTO vShipment + SELECT dated INTO vShipment FROM `time` WHERE `year` = vYear AND `week` = vWeek AND WEEKDAY(dated) = vWeekDay; @@ -68246,52 +68250,52 @@ BEGIN JOIN vn.saleCloned sc ON sc.saleOriginalFk = saleOrig.id JOIN vn.sale saleClon ON saleClon.id = sc.saleClonedFk JOIN vn.ticket tClon ON tClon.id = saleClon.ticketFk - WHERE tOrig.id = vTicketFk AND tClon.isDeleted = FALSE AND DATE(tClon.shipped) = vShipment) > 0 + WHERE tOrig.id = vTicketFk AND tClon.isDeleted = FALSE AND DATE(tClon.shipped) = vShipment) > 0 THEN ITERATE myLoop; END IF; - + IF vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk + SELECT agencyModeFk INTO vAgencyModeFk FROM address WHERE clientFk = vClientFk AND isDefaultAddress; END IF; - + CALL vn.zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); SET vLanding = NULL; SELECT landed INTO vLanding from tmp.zoneGetLanded LIMIT 1; - + CALL ticket_add( - vClientFk, - vShipment, - vWarehouseFk, - vCompanyFk, - vAddressFk, - vAgencyModeFk, - NULL, - vLanding, - account.myUser_getId(), - FALSE, + vClientFk, + vShipment, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + NULL, + vLanding, + account.myUser_getId(), + FALSE, vNewTicket); IF (vLanding IS NULL) THEN - + SELECT e.email INTO vSalesPersonEmail FROM vn.client c JOIN vn.worker sp ON sp.id = c.salesPersonFk JOIN account.emailUser e ON e.userFk = sp.userFk WHERE c.id = vClientFk; - + SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicketFk, ' para el dia: ', vShipment); - SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, - ' para el dia: ', vShipment, - ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, + SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, + ' para el dia: ', vShipment, + ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, ' pero ha que revisar las fechas y la agencia'); - + SELECT COUNT(*) INTO vMailSent - FROM vn.mail - WHERE receiver = vSalesPersonEmail + FROM vn.mail + WHERE receiver = vSalesPersonEmail AND subject = vSubject; IF NOT vMailSent THEN @@ -68299,37 +68303,37 @@ BEGIN END IF; CALL vn.ticketStateUpdate (vNewTicket, 'FIXING'); END IF; - + INSERT INTO vn.sale (ticketFk, itemFk, concept, quantity, price, discount, priceFixed, isPriceFixed) SELECT vNewTicket, saleOrig.itemFk , saleOrig.concept , saleOrig.quantity, saleOrig.price , saleOrig.discount, saleOrig.priceFixed, saleOrig.isPriceFixed - FROM vn.sale saleOrig - WHERE saleOrig.ticketFk = vTicketFk; - + FROM vn.sale saleOrig + WHERE saleOrig.ticketFk = vTicketFk; + INSERT IGNORE INTO vn.saleCloned(saleOriginalFk, saleClonedFk) - SELECT saleOriginal.id, saleClon.id + SELECT saleOriginal.id, saleClon.id FROM vn.sale saleOriginal JOIN vn.sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity WHERE saleOriginal.ticketFk = vTicketFk AND saleClon.ticketFk = vNewTicket; - + INSERT INTO ticketRequest (description,ordered,shipped,quantity,price,itemFk,clientFk,response, - total,buyed,requesterFk,attenderFk,ticketFk) + total,buyed,requesterFk,attenderFk,ticketFk) SELECT description,ordered,shipped,quantity,price,itemFk,clientFk,response, - total,buyed,requesterFk,attenderFk,vNewTicket + total,buyed,requesterFk,attenderFk,vNewTicket FROM ticketRequest WHERE ticketFk =vTicketFk; - + INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) VALUES(vNewTicket,4,CONCAT('turno desde ticket: ',vTicketFk)) - ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); - + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); + INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) VALUES(vNewTicket,1,'ATENCION: Contiene lineas de TURNO') - ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); - + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); + CALL vn.ticketCalculateClon(vNewTicket, vTicketFk); END; END LOOP; CLOSE rsTicket; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68349,7 +68353,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_close`() BEGIN /** - * Realiza el cierre de todos los + * Realiza el cierre de todos los * tickets de la tabla tmp.ticket_close. * * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar @@ -68367,7 +68371,7 @@ BEGIN DECLARE cur CURSOR FOR SELECT ticketFk FROM tmp.ticket_close; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; @@ -68377,7 +68381,7 @@ BEGIN proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCurTicketFk; IF vDone THEN @@ -68395,12 +68399,12 @@ BEGIN c.hasToInvoice INTO vClientFk, vIsTaxDataChecked, - vCompanyFk, + vCompanyFk, vShipped, vHasDailyInvoice, vWithPackage, vHasToInvoice - FROM ticket t + 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 @@ -68409,22 +68413,22 @@ BEGIN INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) (SELECT vCurTicketFk, p.id, COUNT(*) - FROM expedition e + FROM expedition e JOIN packaging p ON p.itemFk = e.freightItemFk WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable AND vWithPackage GROUP BY p.itemFk); -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) (SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1 - FROM expedition e + FROM expedition e JOIN item i ON i.id = e.freightItemFk LEFT JOIN packaging p ON p.itemFk = i.id WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 AND getSpecialPrice(e.freightItemFk, vClientFk) > 0 GROUP BY e.freightItemFk); - + IF(vHasDailyInvoice) AND vHasToInvoice THEN -- Facturacion rapida @@ -68432,10 +68436,10 @@ BEGIN -- Facturar si está contabilizado IF vIsTaxDataChecked THEN CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, NULL, NULL, vNewInvoiceId); @@ -68509,11 +68513,11 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentMakeUpdate`(IN vTic IN vLanded DATE, IN vIsDeleted TINYINT(1), IN vHasToBeUnrouted TINYINT(1), IN vOption INT) BEGIN - + /** * Modifica en el ticket los campos que se le pasan por parámetro * y cambia sus componentes - * + * * @param vTicketFk Id del ticket a modificar * @param vClientFk nuevo cliente * @param vNickname nuevo alias @@ -68528,29 +68532,29 @@ BEGIN * @param vHasToBeUnrouted si se le elimina la ruta al ticket * @param vOption opcion para el case del proc ticketComponentUpdateSale */ - + DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE); - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus FROM tmp.zoneGetShipped WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.nickname = vNickname, t.agencyModeFk = vAgencyModeFk, @@ -68565,12 +68569,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -68608,7 +68612,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentPreview`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk SMALLINT) @@ -68624,7 +68628,7 @@ BEGIN * * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost) */ - DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasDataChanged BOOL DEFAULT FALSE; DECLARE vHasAddressChanged BOOL; DECLARE vHasZoneChanged BOOL DEFAULT FALSE; DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; @@ -68635,8 +68639,8 @@ BEGIN DECLARE vHasChangeAll BOOL DEFAULT FALSE; - SELECT DATE(landed) <> vLanded, - addressFk <> vAddressFk, + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, zoneFk <> vZoneFk, warehouseFk <> vWarehouseFk INTO @@ -68659,15 +68663,15 @@ BEGIN SET vAgencyModeTypeRateFk = 6; END IF; - SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped FROM zone WHERE id = vZoneFk; - + CALL buyUltimate(vWarehouseFk, vShipped); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( - SELECT + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT vWarehouseFk AS warehouseFk, NULL AS available, s.itemFk, @@ -68687,9 +68691,9 @@ BEGIN JOIN sale s ON s.id = sc.saleFk JOIN ticket t ON t.id = s.ticketFk JOIN `component` c ON c.id = sc.componentFk - WHERE s.ticketFk = vTicketFk - AND (c.isRenewable = FALSE - OR + WHERE s.ticketFk = vTicketFk + AND (c.isRenewable = FALSE + OR (NOT vHasChangeAll AND (NOT (c.typeFk <=> vAddressTypeRateFk OR c.typeFk <=> vAgencyModeTypeRateFk)))); @@ -68721,41 +68725,41 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruck`(vWarehouserFk INT, vHour INT, vMinute INT) -BEGIN - - DECLARE done INT DEFAULT FALSE; - DECLARE vTicketFk INT; - DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - CALL vn.productionControl(vWarehouserFk,0) ; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - SELECT ticketFk - FROM tmp.productionBuffer - WHERE shipped = util.VN_CURDATE() - AND problem LIKE '%I:%' - AND (HH <= vHour OR HH = vHour AND mm < vMinute) - AND alertLevel = 0; - - OPEN cur1; - - read_loop: LOOP - - FETCH cur1 INTO vTicketFk; - - IF done THEN - LEAVE read_loop; - END IF; - - CALL vn.ticket_DelayTruckSplit(vTicketFk); - - END LOOP; - - CLOSE cur1; - +BEGIN + + DECLARE done INT DEFAULT FALSE; + DECLARE vTicketFk INT; + DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + CALL vn.productionControl(vWarehouserFk,0) ; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT ticketFk + FROM tmp.productionBuffer + WHERE shipped = util.VN_CURDATE() + AND problem LIKE '%I:%' + AND (HH <= vHour OR HH = vHour AND mm < vMinute) + AND alertLevel = 0; + + OPEN cur1; + + read_loop: LOOP + + FETCH cur1 INTO vTicketFk; + + IF done THEN + LEAVE read_loop; + END IF; + + CALL vn.ticket_DelayTruckSplit(vTicketFk); + + END LOOP; + + CLOSE cur1; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68774,52 +68778,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) BEGIN - + /* * Splita las lineas de ticket que no estan ubicadas - * + * */ - + DECLARE vNewTicketFk INT; DECLARE vTotalLines INT; DECLARE vLinesToSplit INT; DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - + SELECT COUNT(*) INTO vTotalLines - FROM vn.sale + FROM vn.sale WHERE ticketFk = vTicketFk; - + CREATE TEMPORARY TABLE tmp.SalesToSplit SELECT s.id saleFk FROM vn.ticket t - JOIN vn.sale s ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk + JOIN vn.sale s ON t.id = s.ticketFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk WHERE s.quantity > IFNULL(issw.visible, 0) AND s.quantity > 0 AND s.isPicked = FALSE AND s.reserved = FALSE AND t.id = vTicketFk; - + SELECT COUNT(*) INTO vLinesToSplit FROM tmp.SalesToSplit; - + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - + SET vNewTicketFk = vTicketFk; - + ELSE - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + CALL vn.ticketStateUpdate(vNewTicketFk, 'FIXING'); - + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; @@ -69191,37 +69195,37 @@ BEGIN * @param vTicketFk -> Ticket * @param vDatedNew -> Nueva fecha * @return Sales con Movible -*/ +*/ DECLARE vDatedOld DATETIME; SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY); SELECT t.shipped INTO vDatedOld - FROM ticket t + FROM ticket t WHERE t.id = vTicketFk; - CALL itemStock(vWarehouseFk, vDatedNew, NULL); + CALL itemStock(vWarehouseFk, vDatedNew, NULL); CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL); - - SELECT s.id, - s.itemFk, - s.quantity, - s.concept, - s.price, + + SELECT s.id, + s.itemFk, + s.quantity, + s.concept, + s.price, s.reserved, - s.discount, - i.image, - i.subName, + s.discount, + i.image, + i.subName, il.stock + IFNULL(im.amount, 0) AS movable FROM ticket t JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk + JOIN item i ON i.id = s.itemFk LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk AND im.warehouseFk = vWarehouseFk LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk WHERE t.id = vTicketFk; DROP TEMPORARY TABLE IF EXISTS tmp.itemList; - DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69250,10 +69254,10 @@ BEGIN CALL sale_getProblems(vIsTodayRelative); DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems + CREATE TEMPORARY TABLE tmp.ticket_problems (PRIMARY KEY (ticketFk)) ENGINE = MEMORY - SELECT + SELECT ticketFk, MAX(p.isFreezed) AS isFreezed, MAX(p.risk) AS risk, @@ -69270,7 +69274,7 @@ BEGIN GROUP BY ticketFk; UPDATE tmp.ticket_problems tp - SET tp.totalProblems = + SET tp.totalProblems = ( (tp.isFreezed) + IF(tp.risk, TRUE, FALSE) + @@ -69323,17 +69327,17 @@ BEGIN (saleFk INT PRIMARY KEY, ticketFk INT, problem VARCHAR(1)) ENGINE = MEMORY; - + INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'F' FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -69343,16 +69347,16 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'I' - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -69362,7 +69366,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'R' FROM vn.ticket t @@ -69372,7 +69376,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -69383,7 +69387,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketsToSplit; CREATE TEMPORARY TABLE tmp.ticketsToSplit @@ -69404,11 +69408,11 @@ BEGIN JOIN vn.ticket t ON t.id = ss.ticketFk JOIN vn.sale s ON s.id = ss.saleFk JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk GROUP BY ss.ticketFk; - - SELECT - ts.*, + + SELECT + ts.*, t.id ticketFuture, st.name state, zc.`hour` tfEtd, @@ -69417,23 +69421,23 @@ BEGIN FROM tmp.ticketsToSplit ts LEFT JOIN vn.ticketState ts2 ON ts2.ticketFk = ts.ticketFk LEFT JOIN vn.state st ON st.id = ts2.stateFk - LEFT JOIN vn.ticket t - ON t.id != ts.ticketFk + LEFT JOIN vn.ticket t + ON t.id != ts.ticketFk AND t.addressFk = ts.addressFk AND t.shipped BETWEEN vDated AND util.dayend(vDated) LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated LEFT JOIN vn.sale s ON s.ticketFk = t.id LEFT JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id + LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id LEFT JOIN vn.state st2 ON st2.id = tst.stateFk - WHERE (t.id IS NULL + WHERE (t.id IS NULL OR (vDated > util.VN_CURDATE()) OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`)) AND ts.etd <= vHour GROUP BY ts.ticketFk, t.id ORDER BY ts.etd, ts.ticketFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.ticketsToSplit; END ;; DELIMITER ; @@ -69470,7 +69474,7 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + IF vTaxArea > '' THEN UPDATE tmp.addressTaxArea SET areaFk = vTaxArea; @@ -69542,8 +69546,8 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) ENGINE = MEMORY - SELECT ticketFk, - taxableBase, + SELECT ticketFk, + taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax, code FROM tmp.ticketTax @@ -69575,24 +69579,24 @@ BEGIN DECLARE vAddressFk INT; DECLARE vAgencyModeFk INT; DECLARE vWarehouseFk INT; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT id, landed, addressFk, agencyModeFk, warehouseFk FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1; - + OPEN vCursor; REPEAT FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk; CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - + UPDATE vn.ticket t JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk SET t.zoneFk = zgs.zoneFk WHERE t.id = vFechedTicket; - + UNTIL vDone END REPEAT; DROP TEMPORARY TABLE tmp.zoneGetShipped; - + CLOSE vCursor; END ;; DELIMITER ; @@ -69611,24 +69615,24 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_merge`(vSelf INT, vTicketTargetFk INT) -BEGIN - - /** - * Fusiona el primer ticket al segundo - * - * @param vSelf Número de ticket a fusionar - * @param vTicketTargetFk Ticket destino - * - */ - - UPDATE vn.sale s - SET s.ticketFk = vTicketTargetFk - WHERE s.ticketFk = vSelf; - - UPDATE vn.ticket t - SET t.shipped = TIMESTAMPADD(YEAR, - YEAR(util.VN_NOW()) MOD 2000, t.shipped ) - WHERE t.id = vSelf; - +BEGIN + + /** + * Fusiona el primer ticket al segundo + * + * @param vSelf Número de ticket a fusionar + * @param vTicketTargetFk Ticket destino + * + */ + + UPDATE vn.sale s + SET s.ticketFk = vTicketTargetFk + WHERE s.ticketFk = vSelf; + + UPDATE vn.ticket t + SET t.shipped = TIMESTAMPADD(YEAR, - YEAR(util.VN_NOW()) MOD 2000, t.shipped ) + WHERE t.id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69647,14 +69651,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_priceDifference`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk INT) BEGIN /** * Devuelve las diferencias de precio de los movimientos de un ticket. - * + * * @param vTicketFk Id del ticket * @param vLanded Fecha de recepcion * @param vAddressFk Id del consignatario @@ -69663,26 +69667,26 @@ BEGIN */ CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - SELECT s.itemFk, - i.name, - i.size, - i.category, - IFNULL(s.quantity, 0) AS quantity, - IFNULL(s.price, 0) AS price, + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, ROUND(SUM(tc.cost), 2) AS newPrice, s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, s.id AS saleFk FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = vWarehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk - WHERE t.id = vTicketFk - AND IF(sc.componentFk IS NULL - AND c.classRate IS NOT NULL, FALSE, TRUE) + LEFT JOIN `component` c ON c.id = tc.componentFk + WHERE t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND c.classRate IS NOT NULL, FALSE, TRUE) GROUP BY s.id ORDER BY s.id; DROP TEMPORARY TABLE tmp.ticketComponentPreview; @@ -69703,28 +69707,28 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vTicketId INT) -BEGIN -/** - * Calcula y guarda el total con/sin IVA en un ticket. - * - * @param vTicketId Identificador del ticket - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT vTicketId ticketFk; - - CALL ticketGetTotal; - - UPDATE ticket t - JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id - SET t.totalWithVat = tt.total, - t.totalWithoutVat = tt.totalWithoutVat; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTotal; +BEGIN +/** + * Calcula y guarda el total con/sin IVA en un ticket. + * + * @param vTicketId Identificador del ticket + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + ENGINE = MEMORY + SELECT vTicketId ticketFk; + + CALL ticketGetTotal; + + UPDATE ticket t + JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id + SET t.totalWithVat = tt.total, + t.totalWithoutVat = tt.totalWithoutVat; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69742,91 +69746,91 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN) -proc: BEGIN - -/** - * Este procedimiento recalcula los componentes de un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @param vIsTicketEditable si no se quiere forzar llamar con NULL - */ - 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 AND IFNULL(t.refFk,'') = '' - INTO vIsTicketEditable - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - END IF; - - SELECT t.warehouseFk, - t.shipped, - t.addressFk, - t.agencyModeFk, - t.landed, - t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE t.id = vTicketFk; - - CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - - IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN - CALL util.throw('There is no zone for these parameters'); - END IF; - - IF vLanded IS NULL OR vZoneFk IS NULL THEN - - UPDATE ticket t - SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) - WHERE t.id = vTicketFk AND t.landed IS NULL; - - IF vZoneFk IS NULL THEN - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; - UPDATE ticket t - SET t.zoneFk = vZoneFk - WHERE t.id = vTicketFk AND t.zoneFk IS NULL; - END IF; - - END IF; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - -- rellena la tabla buyUltimate con la ultima compra - CALL buyUltimate (vWarehouseFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk, vZoneFk zoneFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL catalog_componentPrepare(); - CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - - 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; - - -- si el ticket esta facturado, respeta los precios - CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); - - CALL catalog_componentPurge(); - DROP TEMPORARY TABLE - tmp.buyUltimate, - tmp.sale; +proc: BEGIN + +/** + * Este procedimiento recalcula los componentes de un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @param vIsTicketEditable si no se quiere forzar llamar con NULL + */ + 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 AND IFNULL(t.refFk,'') = '' + INTO vIsTicketEditable + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + + SELECT t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, + t.landed, + t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE t.id = vTicketFk; + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); + + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN + CALL util.throw('There is no zone for these parameters'); + END IF; + + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + UPDATE ticket t + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + WHERE t.id = vTicketFk AND t.landed IS NULL; + + IF vZoneFk IS NULL THEN + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + UPDATE ticket t + SET t.zoneFk = vZoneFk + WHERE t.id = vTicketFk AND t.zoneFk IS NULL; + END IF; + + END IF; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk, vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + 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; + + -- si el ticket esta facturado, respeta los precios + CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); + + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.sale; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70075,40 +70079,40 @@ proc:BEGIN SELECT COUNT(*) INTO vProblemLines FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - + SELECT count(*) INTO vTotalLines - FROM vn.sale s + FROM vn.sale s WHERE s.ticketFk = vTicketFk; - + SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - + UPDATE vn.ticket SET landed = vDated + 1, shipped = vDated, nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) WHERE id = vTicketFk; - + SELECT CONCAT("Se ha cambiado el ticket ", vTicketFk, " al dia ", vDated); LEAVE proc; - + END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s + + UPDATE vn.sale s JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al ticket existente ", vTicketFutureFk,"(", vDated,")"); LEAVE proc; - + END IF; -- Ticket nuevo @@ -70119,18 +70123,18 @@ proc:BEGIN SET t.landed = vDated + 1, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, - t.zoneFk = pc.defaultZone + t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al nuevo ticket ", vTicketFutureFk,"(", vDated,")"); END ;; DELIMITER ; @@ -70269,43 +70273,43 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT) BEGIN - + DECLARE vNeedToSplit BOOLEAN; DECLARE vNewTicketFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmpSale; - + CREATE TEMPORARY TABLE tmpSale SELECT DISTINCT s.id - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk - JOIN vn.packagingConfig pc + JOIN vn.packagingConfig pc WHERE t.id = vTicketFk AND ( s.quantity MOD IFNULL(iss.packing,1) != 0 - OR + OR IFNULL(iss.packing,1) = 1 - OR + OR i.`size` <= pc.previousPreparationMinimumSize ); - - SELECT COUNT(*) + + SELECT COUNT(*) INTO vNeedToSplit - FROM tmpSale; - + FROM tmpSale; + IF vNeedToSplit THEN - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - + UPDATE vn.sale s - JOIN vn.tmpSale ts ON ts.id = s.id + JOIN vn.tmpSale ts ON ts.id = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + DROP TEMPORARY TABLE tmpSale; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70336,7 +70340,7 @@ BEGIN WHERE ot.description = 'Peso Aduana' AND t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -70345,9 +70349,9 @@ BEGIN JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk WHERE t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SET vRatio = vRealWeight / vTheorycalWeight; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight; CREATE TEMPORARY TABLE tmp.ticketWeight @@ -70368,7 +70372,7 @@ BEGIN AND t.shipped BETWEEN vDated AND util.dayend(vDated) GROUP BY ib.ediBotanic, o.code; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70388,7 +70392,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * Horas que debe trabajar un empleado según contrato y día. + * Horas que debe trabajar un empleado según contrato y día. * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl * @table tmp.user(userFk) @@ -70397,10 +70401,10 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; CREATE TEMPORARY TABLE tmp.timeBusinessCalculate - SELECT dated, + SELECT dated, businessFk, - userFk, - departmentFk, + userFk, + departmentFk, hourStart, hourEnd, timeTable, @@ -70418,8 +70422,8 @@ BEGIN FROM(SELECT t.dated, b.id businessFk, w.userFk, - b.departmentFk, - IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5) ORDER BY j.start ASC SEPARATOR ' - ')) hourStart , + b.departmentFk, + IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5) ORDER BY j.start ASC SEPARATOR ' - ')) hourStart , IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) hourEnd, IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5), " - ", LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) timeTable, IF(j.start = NULL, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)), 0)) timeWorkSeconds, @@ -70435,7 +70439,7 @@ BEGIN LEFT JOIN workCenter wc ON wc.id = b.workcenterFK LEFT JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk LEFT JOIN postgresql.journey j ON j.business_id = b.id AND j.day_id = WEEKDAY(t.dated) + 1 - LEFT JOIN postgresql.calendar_employee ce ON ce.businessFk = b.id AND ce.date = t.dated + LEFT JOIN postgresql.calendar_employee ce ON ce.businessFk = b.id AND ce.date = t.dated LEFT JOIN absenceType at2 ON at2.id = ce.calendar_state_id WHERE t.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY w.userFk, t.dated @@ -70444,25 +70448,25 @@ BEGIN UPDATE tmp.timeBusinessCalculate t LEFT JOIN postgresql.journey j ON j.business_id = t.businessFk SET t.timeWorkSeconds = t.hoursWeek / 5 * 3600, - t.timeWorkSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), - t.timeWorkDecimal = t.hoursWeek / 5, + t.timeWorkSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), + t.timeWorkDecimal = t.hoursWeek / 5, t.timeBusinessSeconds = t.hoursWeek / 5 * 3600, - t.timeBusinessSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), + t.timeBusinessSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), t.timeBusinessDecimal = t.hoursWeek / 5 WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND j.journey_id IS NULL ; - UPDATE tmp.timeBusinessCalculate t + UPDATE tmp.timeBusinessCalculate t SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionRate) , t.timeWorkSexagesimal = SEC_TO_TIME ((t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)) * 3600), t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate) - WHERE permissionRate <> 0; + WHERE permissionRate <> 0; - UPDATE tmp.timeBusinessCalculate t + UPDATE tmp.timeBusinessCalculate t JOIN calendarHolidays ch ON ch.dated = t.dated - JOIN business b ON b.id = t.businessFk - AND b.workcenterFk = ch.workcenterFk + JOIN business b ON b.id = t.businessFk + AND b.workcenterFk = ch.workcenterFk SET t.timeWorkSeconds = 0, - t.timeWorkSexagesimal = 0, + t.timeWorkSexagesimal = 0, t.timeWorkDecimal = 0, t.permissionrate = 1, t.type = 'Festivo' @@ -70493,16 +70497,16 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.userFk WHERE userFk IS NOT NULL; - + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70522,21 +70526,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -70561,19 +70565,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByUser`(vUser BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -70600,17 +70604,17 @@ BEGIN * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u JOIN vn.worker w ON w.userFk = u.id WHERE w.id = vWorkerFk; - + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -70633,21 +70637,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`(vDatedFrom D BEGIN /* * @param vDatedFrom - * @param vDatedTo + * @param vDatedTo * Calculo de horas trabajadas por empleado y dia, sin tener encuenta los dias con fichadas incorrectas * segun la tabla tmp.timeControlError * @return tmp.timeControlCalculate (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) */ DECLARE vHourToSeconds INTEGER; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; + DECLARE vDatedToTomorrow DATETIME; DECLARE vTimeToBreakTime INT; DECLARE vBreakTime INT; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; - - SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime + + SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime FROM workerTimeControlConfig LIMIT 1; CALL timeControl_getError(vDatedFrom, vDatedTo); @@ -70656,9 +70660,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction, TRUE isReal FROM workerTimeControl wtc @@ -70668,10 +70672,10 @@ BEGIN AND tce.id IS NULL ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -70760,7 +70764,7 @@ BEGIN IF(direction='in', @vDated := DATE(wtc.timed), @vDated) dated, wtc.userFk FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed, wtc.id + ORDER BY wtc.userFk, wtc.timed, wtc.id LIMIT 10000000000000000000 )sub GROUP BY sub.userFk, sub.dated @@ -70771,9 +70775,9 @@ BEGIN SET @vLastTimed := 0; DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux2; - CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 + CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 SELECT * - FROM tmp.workerTimeControl + FROM tmp.workerTimeControl WHERE timed BETWEEN vDatedFromYesterday AND vDatedTo ORDER BY userFk, timed, id; @@ -70832,16 +70836,16 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.userFk WHERE userFk IS NOT NULL; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70861,21 +70865,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -70900,19 +70904,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByUser`(vUserF BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -70935,21 +70939,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByWorker`(vWor BEGIN /** - * @param vWorkerFk + * @param vWorkerFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u JOIN vn.worker w ON w.userFk = u.id WHERE w.id = vWorkerFk; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -70972,12 +70976,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_getError`(vDatedFrom DA BEGIN /* * @param vDatedFrom - * @param vDatedTo + * @param vDatedTo * @table tmp.`user`(userFk) * Fichadas incorrectas de las cuales no se puede calcular horas trabajadas * @return tmp.timeControlError (id) */ - DECLARE vDayMaxTime INTEGER; + DECLARE vDayMaxTime INTEGER; SET @journeyCounter := 0; SET @lastUserFk := NULL; @@ -70985,16 +70989,16 @@ BEGIN SELECT dayMaxTime INTO vDayMaxTime FROM workerTimeControlConfig LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - CREATE TEMPORARY TABLE tmp.timeControl + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + CREATE TEMPORARY TABLE tmp.timeControl (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT sub.id, - sub.direction, + sub.direction, sub.timed, IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter, - @lastUserFk := sub.userFk workerFk, - IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) + @lastUserFk := sub.userFk workerFk, + IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) FROM ( SELECT DISTINCT wtc.id, wtc.direction, @@ -71005,36 +71009,36 @@ BEGIN WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY) ORDER BY wtc.userFk, wtc.timed ) sub; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; CREATE TEMPORARY TABLE tmp.timeControlAux (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT * FROM tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; - CREATE TEMPORARY TABLE tmp.timeControlError + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; + CREATE TEMPORARY TABLE tmp.timeControlError (INDEX(id)) ENGINE = MEMORY - SELECT id + SELECT id FROM tmp.timeControlAux tca JOIN ( - SELECT journeyCounter, + SELECT journeyCounter, UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork, - SUM(direction = 'in') totalIn, + SUM(direction = 'in') totalIn, SUM(direction = 'out') totalOut, timed FROM tmp.timeControl GROUP BY journeyCounter - HAVING COUNT(*) MOD 2 = 1 - OR totalIn <> 1 - OR totalOut <> 1 + HAVING COUNT(*) MOD 2 = 1 + OR totalIn <> 1 + OR totalOut <> 1 OR timeWork >= vDayMaxTime )sub ON sub.journeyCounter = tca.journeyCounter WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71057,7 +71061,7 @@ proc: BEGIN * deprecated call workerTimeControl_check */ CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71075,27 +71079,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_checkStatus`() -BEGIN -/** - * - * Envia mail con los cobros web no - * trasladados a la ficha del cliente. - * - */ - INSERT INTO mail (receiver,replyTo,subject,body) - SELECT 'administracion@verdnatura.es', - 'noreply@verdnatura.es', - CONCAT('Cobro web no trasladado a la ficha del cliente ', t.clientFk), - CONCAT('Hay un importe de ', t.amount/100, '€ del cliente ', t.clientFk, ' con fecha ', t.created, - ', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en - - https://salix.verdnatura.es/#!/client/',t.clientFk,'/web-payment') - FROM hedera.tpvTransaction t - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - AND t.created < DATE_ADD(util.VN_NOW(),INTERVAL - 2 DAY) - GROUP BY t.clientFk; - +BEGIN +/** + * + * Envia mail con los cobros web no + * trasladados a la ficha del cliente. + * + */ + INSERT INTO mail (receiver,replyTo,subject,body) + SELECT 'administracion@verdnatura.es', + 'noreply@verdnatura.es', + CONCAT('Cobro web no trasladado a la ficha del cliente ', t.clientFk), + CONCAT('Hay un importe de ', t.amount/100, '€ del cliente ', t.clientFk, ' con fecha ', t.created, + ', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en + + https://salix.verdnatura.es/#!/client/',t.clientFk,'/web-payment') + FROM hedera.tpvTransaction t + WHERE t.receiptFk IS NULL + AND t.status = 'ok' + AND t.created < DATE_ADD(util.VN_NOW(),INTERVAL - 2 DAY) + GROUP BY t.clientFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71114,12 +71118,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT) BEGIN - - SELECT w1.name AS ORI, - w2.name AS DES, + + SELECT w1.name AS ORI, + w2.name AS DES, tr.shipped shipment, tr.landed landing, - a.name Agencia, + a.name Agencia, s.name Proveedor, e.id Id_Entrada, e.invoiceNumber Referencia, @@ -71127,18 +71131,18 @@ BEGIN vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.travel tr ON tr.id = e.travelFk + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.agencyMode a ON a.id = tr.agencyModeFk - JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk - JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk - JOIN vn.volumeConfig vc - JOIN vn.item i ON i.id = b.itemFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk JOIN vn.itemType it ON it.id = i.typeFk WHERE tr.id = vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71194,11 +71198,11 @@ BEGIN * @param vShipped The shipment date * @param vLanded The landing date */ - + IF vLanded < vShipped THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment'; - END IF; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71274,146 +71278,146 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( - IN vTravelFk INT, - IN vDateStart DATE, - IN vDateEnd DATE, - IN vWarehouseOutFk INT, - IN vWarehouseInFk INT, - IN vRef VARCHAR(255), - IN vAgencyModeFk INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( + IN vTravelFk INT, + IN vDateStart DATE, + IN vDateEnd DATE, + IN vWarehouseOutFk INT, + IN vWarehouseInFk INT, + IN vRef VARCHAR(255), + IN vAgencyModeFk INT, OUT vNewTravelFk INT) -BEGIN -/** - * Clona un travel junto con sus entradas y compras - * - * @param vTravelFk travel plantilla a clonar - * @param vDateStart fecha del shipment del nuevo travel - * @param vDateEnd fecha del landing del nuevo travel - * @param vWarehouseOutFk fecha del salida del nuevo travel - * @param vWarehouseInFk warehouse de landing del nuevo travel - * @param vRef referencia del nuevo travel - * @param vAgencyModeFk del nuevo travel - * @param vNewTravelFk id del nuevo travel - */ - DECLARE vEntryNew INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - 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 CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION/*, 1062 Duplicate key*/ - BEGIN - ROLLBACK; - - END; - - START TRANSACTION; - INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3, kg - FROM travel - WHERE id = vTravelFk; - - SET vNewTravelFk = LAST_INSERT_ID(); - CALL logAdd(vNewTravelFk, 'insert', 'travel', CONCAT('clona travel ',vTravelFk)); - SET vDone = FALSE; - SET @isModeInventory = TRUE; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO entry ( - supplierFk, - invoiceNumber, - isExcludedFromAvailable, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - invoiceNumber, - isExcludedFromAvailable, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vNewTravelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - CALL logAdd(vEntryNew, 'insert', 'entry', CONCAT('clona entrada ',vAuxEntryFk)); - INSERT INTO buy ( - entryFk, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - printedStickers, - isChecked, - weight, - itemOriginalFk) - SELECT vEntryNew, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - printedStickers, - isChecked, - weight, - itemOriginalFk - FROM buy - WHERE entryFk = vAuxEntryFk; - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - SET @isModeInventory = FALSE; - CLOSE vRsEntry; - COMMIT; +BEGIN +/** + * Clona un travel junto con sus entradas y compras + * + * @param vTravelFk travel plantilla a clonar + * @param vDateStart fecha del shipment del nuevo travel + * @param vDateEnd fecha del landing del nuevo travel + * @param vWarehouseOutFk fecha del salida del nuevo travel + * @param vWarehouseInFk warehouse de landing del nuevo travel + * @param vRef referencia del nuevo travel + * @param vAgencyModeFk del nuevo travel + * @param vNewTravelFk id del nuevo travel + */ + DECLARE vEntryNew INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + 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 CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION/*, 1062 Duplicate key*/ + BEGIN + ROLLBACK; + + END; + + START TRANSACTION; + INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vNewTravelFk = LAST_INSERT_ID(); + CALL logAdd(vNewTravelFk, 'insert', 'travel', CONCAT('clona travel ',vTravelFk)); + SET vDone = FALSE; + SET @isModeInventory = TRUE; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry ( + supplierFk, + invoiceNumber, + isExcludedFromAvailable, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + invoiceNumber, + isExcludedFromAvailable, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vNewTravelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + CALL logAdd(vEntryNew, 'insert', 'entry', CONCAT('clona entrada ',vAuxEntryFk)); + INSERT INTO buy ( + entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + printedStickers, + isChecked, + weight, + itemOriginalFk) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + printedStickers, + isChecked, + weight, + itemOriginalFk + FROM buy + WHERE entryFk = vAuxEntryFk; + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + SET @isModeInventory = FALSE; + CLOSE vRsEntry; + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71458,11 +71462,11 @@ BEGIN SELECT COUNT(*) INTO vTotalEntries FROM entry WHERE travelFk = vTravelFk; - + UPDATE travel SET totalEntries = vTotalEntries WHERE id = vTravelFk; - + DELETE FROM travelRecalc WHERE travelFk = vTravelFk; END LOOP; @@ -71488,7 +71492,7 @@ BEGIN /* * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores - * + * */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vWorkerName VARCHAR(50); @@ -71500,7 +71504,7 @@ BEGIN SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'), u.name FROM tmp.travel ttr - JOIN entry e ON e.travelFk = ttr.id + JOIN entry e ON e.travelFk = ttr.id JOIN buy b ON b.entryFk = e.id JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk @@ -71508,19 +71512,19 @@ BEGIN GROUP BY u.name; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; + SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; - + DROP TEMPORARY TABLE IF EXISTS tmp.travel; CREATE TEMPORARY TABLE tmp.travel SELECT tr.id,tr.landed FROM travel tr - JOIN entry e ON e.travelFk = tr.id + JOIN entry e ON e.travelFk = tr.id WHERE tr.landed = util.tomorrow() AND e.isRaid GROUP BY tr.id; @@ -71582,7 +71586,7 @@ proc: BEGIN IF vSelf IS NULL THEN LEAVE proc; END IF; - + INSERT IGNORE INTO travelRecalc SET travelFk = vSelf; END ;; DELIMITER ; @@ -71629,7 +71633,7 @@ BEGIN FROM travelClonedWeekly WHERE travelFk; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; SET vCounter = vSinceWeek; vWeekLoop :LOOP @@ -71659,7 +71663,7 @@ BEGIN SET vCounter = vCounter + 1; END LOOP vWeekLoop; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71677,60 +71681,60 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `typeTagMake`(vTypeFk INT) -BEGIN -/* - * Plantilla para modificar reemplazar todos los tags - * por los valores que tienen los articulos - * - * @param vTypeFk tipo a modificar - * - */ - DELETE it.* - FROM itemTag it - JOIN item i ON i.id = it.itemFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, CONCAT(i.size,' cm'), 1 - FROM item i - JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, i.category, 5 - FROM item i - JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, ink.name, 2 - FROM item i - JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci - JOIN ink ON ink.id = i.inkFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, p.name, 3 - FROM item i - JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci - JOIN producer p ON p.id = i.producerFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, o.name, 4 - FROM item i - JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci - JOIN origin o ON o.id = i.originFk - WHERE i.typeFk = vTypeFk; - /* - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, i.stems, 6 - FROM item i - JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - */ --- CALL itemTagArrangedUpdate(NULL); - +BEGIN +/* + * Plantilla para modificar reemplazar todos los tags + * por los valores que tienen los articulos + * + * @param vTypeFk tipo a modificar + * + */ + DELETE it.* + FROM itemTag it + JOIN item i ON i.id = it.itemFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, CONCAT(i.size,' cm'), 1 + FROM item i + JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, i.category, 5 + FROM item i + JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, ink.name, 2 + FROM item i + JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci + JOIN ink ON ink.id = i.inkFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, p.name, 3 + FROM item i + JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci + JOIN producer p ON p.id = i.producerFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, o.name, 4 + FROM item i + JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci + JOIN origin o ON o.id = i.originFk + WHERE i.typeFk = vTypeFk; + /* + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, i.stems, 6 + FROM item i + JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + */ +-- CALL itemTagArrangedUpdate(NULL); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71751,7 +71755,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `updatePedidosInternos`(vItemFk INT) BEGIN UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk; - + END ;; DELIMITER ; @@ -71771,21 +71775,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `visible_getMisfit`(vSectorFk INT) BEGIN - + /* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica - * + * * @param vSectorFk Identificador de vn.sector - * + * * @return tmp.stockMisfit(itemFk, visible, parked) */ - + DECLARE vCalcVisibleFk INT; DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk); DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit; @@ -71798,17 +71802,17 @@ BEGIN INSERT INTO tmp.stockMisfit(itemFk, parked) SELECT iss.itemFk , sum(iss.visible ) - FROM vn.itemShelvingStock iss - JOIN vn.sector s ON s.id = iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk WHERE vSectorFk IN (s.id, s.sonFk) GROUP BY iss.itemFk; - + INSERT INTO tmp.stockMisfit(itemFk, visible) - SELECT v.item_id , v.visible - FROM cache.visible v - WHERE v.calc_id = vCalcVisibleFk + SELECT v.item_id , v.visible + FROM cache.visible v + WHERE v.calc_id = vCalcVisibleFk ON DUPLICATE KEY UPDATE visible = v.visible; - + DELETE FROM tmp.stockMisfit WHERE visible = parked; @@ -71832,17 +71836,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `warehouseFitting`(IN vWhOrigin INT BEGIN DECLARE vCacheVisibleOriginFk INT; DECLARE vCacheVisibleDestinyFk INT; - + CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin); CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny); - + SELECT i.id itemFk, i.longName, i.size, i.subName, vOrigin.visible AS Origen, vDestiny.visible Destino - + FROM vn.item i JOIN vn.itemType it ON it.id = i.typeFk LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id @@ -71871,13 +71875,13 @@ BEGIN DECLARE vWhOrigin INT; DECLARE vWhDestiny INT; - + SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin FROM vn.travel WHERE id = vTravelFk; - + CALL vn.warehouseFitting(vWhOrigin, vWhDestiny); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71941,7 +71945,7 @@ BEGIN * Calcula los días y horas de vacaciones en función de un contrato y año * * @param vYear - * @param vBusinessFk + * @param vBusinessFk * @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed) */ DECLARE vStarted DATE; @@ -71953,17 +71957,17 @@ BEGIN DECLARE vPayedHolidays DECIMAL(5,2); DECLARE vDifDays INT; - SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), - IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), + SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), + IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), IF(wbt.hasHolidayEntitlement, w.days, 0), c.hours_week, IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays - INTO vStarted, - vEnded, - vDaysHoliday, + INTO vStarted, + vEnded, + vDaysHoliday, vHoursWeek, vPayedHolidays - FROM business b + FROM business b JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk LEFT JOIN postgresql.calendar_labour_type c ON c.calendar_labour_type_id = b.calendarTypeFk @@ -71971,21 +71975,21 @@ BEGIN AND w.year = vYear; DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness; - + IF vStarted < vEnded THEN SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1; - SELECT IFNULL(SUM(holidayEntitlementRate), 0), + SELECT IFNULL(SUM(holidayEntitlementRate), 0), SUM(-(discountRate - 1)) + vPayedHolidays - INTO vDaysToSubtract, - vDaysHolidayEnjoyed + INTO vDaysToSubtract, + vDaysHolidayEnjoyed FROM workerCalendar w JOIN absenceType a ON a.id = w.absenceTypeFk - WHERE w.businessFk = vBusinessFk + WHERE w.businessFk = vBusinessFk AND YEAR(dated) = vYear; END IF; - CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness + CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness ENGINE = MEMORY SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days, @days * (vHoursWeek / 5) hours, @@ -72013,32 +72017,32 @@ BEGIN /** * Calcula los días y horas de vacaciones en función de un trabajador y año * - * @param vYear - * @param vWorkerFk + * @param vYear + * @param vWorkerFk * @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed) - */ + */ DECLARE vDone BOOL; DECLARE vBusinessFk INT; DECLARE cur CURSOR FOR - SELECT b.id + SELECT b.id FROM business b - WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) + WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) AND b.workerFk = vWorkerFk; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - + SET vDone = TRUE; + DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear; CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear - (days DEC(5,2), + (days DEC(5,2), hours DEC(5,2), - daysEnjoyed DEC(5,2), - hoursEnjoyed DEC(5,2)) + daysEnjoyed DEC(5,2), + hoursEnjoyed DEC(5,2)) ENGINE = MEMORY; INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0); - + OPEN cur; l: LOOP @@ -72051,12 +72055,12 @@ BEGIN CALL workerCalendar_calculateBusiness(vYear, vBusinessFk); UPDATE tmp.workerCalendarCalculateYear w - JOIN tmp.workerCalendarCalculateBusiness wc + JOIN tmp.workerCalendarCalculateBusiness wc SET w.days = w.days + wc.days, w.hours = w.hours + wc.hours, w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed, w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed; - + DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness; END LOOP; @@ -72081,7 +72085,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`( vFirstname VARCHAR(50), - vLastName VARCHAR(50), + vLastName VARCHAR(50), vCode CHAR(3), vBossFk INT, vUserFk INT, @@ -72093,7 +72097,7 @@ BEGIN * Create new worker * */ - INSERT INTO worker(id, code, firstName, lastName, userFk, bossFk, fi, birth) + INSERT INTO worker(id, code, firstName, lastName, userFk, bossFk, fi, birth) VALUES (vUserFk, vCode, vFirstname, vLastName, vUserFk, vBossFk, vFi, vBirth); END ;; DELIMITER ; @@ -72160,20 +72164,20 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate; CREATE TEMPORARY TABLE tmp.workerDepartmentByDate ENGINE = MEMORY - SELECT w.userFk, - w.lastName name, - w.firstName firstname, - d.name department, + SELECT w.userFk, + w.lastName name, + w.firstName firstname, + d.name department, d.id departmentFk, - b.started, - d.isProduction, + b.started, + d.isProduction, CAST(12 * b.amount / clt.hours_week / 52 AS DECIMAL(10,2)) costeHora, w.fi nif FROM business b JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = b.calendarTypeFk JOIN department d ON d.id = b.departmentFk JOIN worker w ON w.id = b.workerFk - WHERE b.started <= vDate + WHERE b.started <= vDate AND (b.ended > vDate OR b.ended IS NULL); END ;; DELIMITER ; @@ -72200,18 +72204,18 @@ mainLabel:BEGIN DELETE FROM account.account WHERE id = vUserId; - UPDATE account.user + UPDATE account.user SET role = 2 - WHERE id = vUserId; + WHERE id = vUserId; - DELETE FROM pbx.sip - WHERE user_id = vUserId; + DELETE FROM pbx.sip + WHERE user_id = vUserId; UPDATE `client` c JOIN payMethod p ON p.name = 'CONTADO' SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE WHERE c.id = vUserId; - + UPDATE `client` c SET c.salesPersonFk = null WHERE c.salesPersonFk = vUserId; @@ -72240,12 +72244,12 @@ BEGIN SELECT b.workerFk FROM business b JOIN vn.worker w ON w.id = b.workerFk - JOIN account.account a ON a.id = b.workerFk - LEFT JOIN (SELECT b.workerFk + JOIN account.account a ON a.id = b.workerFk + LEFT JOIN (SELECT b.workerFk FROM business b WHERE (ended IS NULL OR ended >=util.VN_CURDATE()) )sub ON sub.workerFk = a.id - LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk + LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk WHERE sub.workerFk IS NULL AND wd.workerFk IS NULL GROUP BY w.id; @@ -72263,7 +72267,7 @@ BEGIN END WHILE; CLOSE rs; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72327,19 +72331,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerJourney_replace`( - vDatedFrom DATE, - vDatedTo DATE, + vDatedFrom DATE, + vDatedTo DATE, vWorkerFk INT) BEGIN /** - * Actualiza la tabla workerJourney para que actue como caché permanente revisable + * Actualiza la tabla workerJourney para que actue como caché permanente revisable * de las jornadas laborales. * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl * @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos - */ + */ DECLARE vDatedTimeTo DATETIME; - DECLARE vMaxTimePerDay INT; + DECLARE vMaxTimePerDay INT; DECLARE vMinHoursToBreak DECIMAL(10,2); DECLARE vBreakHours DECIMAL(10,2); DECLARE vMonthByYear INT; @@ -72347,57 +72351,57 @@ BEGIN DECLARE vMonthsByYear INT DEFAULT 12; DECLARE vDaysByWeek INT DEFAULT 5; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + DECLARE vDatedToTomorrow DATETIME; + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; SET vDatedTimeTo = util.dayEnd(vDatedTo); - - SELECT minHoursToBreak, breakHours, maxTimePerDay + + SELECT minHoursToBreak, breakHours, maxTimePerDay INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay FROM workerTimeControlConfig; DELETE FROM workerJourney - WHERE dated BETWEEN vDatedFrom AND vDatedTo + WHERE dated BETWEEN vDatedFrom AND vDatedTo AND NOT isPaid AND NOT isUpdated - AND (vWorkerFk IS NULL OR userFK = vWorkerFk); + AND (vWorkerFk IS NULL OR userFK = vWorkerFk); - -- Se inserta todos los días del periodo por worker y business en el rango de fechas. + -- Se inserta todos los días del periodo por worker y business en el rango de fechas. INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) SELECT b.workerFk, t.dated, b.id - FROM business b + FROM business b JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE()) WHERE t.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk) ORDER BY b.workerFk, t.dated, b.id; - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` - SELECT vWorkerFk userFk; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; - END IF; + END IF; UPDATE workerJourney wj JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk - SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, - t.timeWorkDecimal - vBreakHours, + SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, + t.timeWorkDecimal - vBreakHours, t.timeWorkDecimal) AS DECIMAL (10,2)), wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0) WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo AND NOT wj.isPaid AND NOT wj.isUpdated AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk); - - -- NOCTURNIDAD + + -- NOCTURNIDAD CALL timeControl_getError(vDatedFrom, vDatedTimeTo); SET @vIsOdd := TRUE; @@ -72407,9 +72411,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction FROM workerTimeControl wtc JOIN tmp.`user` w ON w.userFk = wtc.userFk @@ -72419,10 +72423,10 @@ BEGIN AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk) ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -72444,9 +72448,9 @@ BEGIN DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' - AND (DATE(@lastTimed) <> date(timed) + IF(@vIsOdd + AND @lastDirection = 'middle' + AND (DATE(@lastTimed) <> date(timed) OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @lastUserFk := userFk, @@ -72460,16 +72464,16 @@ BEGIN SET @lastDirection := NULL; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - lastUserFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + lastUserFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL), DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' + IF(@vIsOdd + AND @lastDirection = 'middle' AND (DATE(@lastTimed)<>date(timed) OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @@ -72482,7 +72486,7 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) SELECT @vCont:= @vCont + 1, - wtc.userFk, + wtc.userFk, util.dayEnd(date(wtc.timed)), 'out' FROM workerTimeControl wtc @@ -72493,8 +72497,8 @@ BEGIN GROUP BY wtc.userFk, DATE(wtc.timed); INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - wtc.userFk, + SELECT @vCont:= @vCont + 1, + wtc.userFk, DATE_ADD(date(wtc.timed), INTERVAL 1 DAY), 'in' FROM workerTimeControl wtc @@ -72520,8 +72524,8 @@ BEGIN IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed), IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated, wtc.userFk, - IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, - workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), + IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, + workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), 0) NigthlyHours, @lastUserFk := userFk FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction @@ -72534,7 +72538,7 @@ BEGIN ) wtc ORDER BY wtc.userFk, wtc.timed )sub - WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo + WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY userFk, sub.dated )night ON night.userFk = wj.userFk AND night.dated = wj.dated SET wj.nocturn = night.NigthlyHours @@ -72545,10 +72549,10 @@ BEGIN -- Horas téoricas y precio de la hora ordinaria UPDATE workerJourney wj JOIN business b ON b.id = wj.businessFk - JOIN postgresql.calendar_labour_type cl + JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk - SET wj.priceOrdinaryHour = - (vMonthsByYear * b.amount) / + SET wj.priceOrdinaryHour = + (vMonthsByYear * b.amount) / (vWeeksByYear * cl.hours_week), wj.contractJourney = cl.hours_week / vDaysByWeek WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo @@ -72556,7 +72560,7 @@ BEGIN AND NOT wj.isPaid AND NOT isUpdated; - -- Precio Extras, Vacaciones y Nocturnas + -- Precio Extras, Vacaciones y Nocturnas UPDATE workerJourney wj JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc FROM time t @@ -72575,18 +72579,18 @@ BEGIN -- Elimina el precio de las horas extras para los contratos parciales. UPDATE workerJourney wj JOIN business b ON b.id = wj.businessFk - JOIN postgresql.calendar_labour_type cl + JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk SET wj.priceExtraHour = 0 WHERE cl.isPartial AND wj.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) - AND NOT wj.isPaid + AND NOT wj.isPaid AND NOT wj.isUpdated; -- Ausencias UPDATE workerJourney wj - JOIN businessCalendar bc ON bc.businessFk = wj.businessFk + JOIN businessCalendar bc ON bc.businessFk = wj.businessFk AND bc.dated = wj.dated JOIN absenceType ab ON ab.id = bc.absenceTypeFk SET wj.permission = ab.permissionRate * wj.contractJourney, @@ -72601,7 +72605,7 @@ BEGIN UPDATE workerJourney SET holiday = IF(DAYNAME(dated)='sábado', 0, total), contractJourney = 0 - WHERE DAYNAME(dated) IN ('sábado', 'domingo') + WHERE DAYNAME(dated) IN ('sábado', 'domingo') AND dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) AND NOT isPaid @@ -72610,8 +72614,8 @@ BEGIN -- Festivos por centro de trabajo UPDATE workerJourney wj JOIN calendarHolidays ch ON ch.dated = wj.dated - JOIN business b ON b.id = wj.businessFk - AND b.workcenterFk = ch.workcenterFk + JOIN business b ON b.id = wj.businessFk + AND b.workcenterFk = ch.workcenterFk SET wj.holiday = wj.total, wj.permission = wj.contractJourney, wj.contractJourney = 0 @@ -72621,7 +72625,7 @@ BEGIN AND NOT wj.isUpdated; -- Horas extras - UPDATE workerJourney + UPDATE workerJourney SET extra = lunch + total - contractJourney WHERE dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) @@ -72650,16 +72654,16 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`() -BEGIN - -/** - * Obtiene los tipos de error para los trabajadores - */ - - SELECT code, description - FROM workerMistakeType - ORDER BY description; - +BEGIN + +/** + * Obtiene los tipos de error para los trabajadores + */ + + SELECT code, description + FROM workerMistakeType + ORDER BY description; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72677,27 +72681,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistake_add`(vWorkerFk INT, vWorkerMistakeTypeFk VARCHAR(10), vUserFk INT ) -BEGIN - -/** - * Añade error al trabajador - * - * @param vWorkerFk id del trabajador al cual se le va a añadir error - * @param vWorkerMistakeTypeFk code del tipo de error - * @param vUserFk id del usuario que pone el error - * - */ - DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vUserFk); - - IF(account.user_hasRole(vWorkerName,'coolerBoss')) - THEN - INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) - VALUES(vWorkerFk, vWorkerMistakeTypeFk); - ELSE - CALL util.throw('No tienes permisos para realizar la acción'); - - END IF; - +BEGIN + +/** + * Añade error al trabajador + * + * @param vWorkerFk id del trabajador al cual se le va a añadir error + * @param vWorkerMistakeTypeFk code del tipo de error + * @param vUserFk id del usuario que pone el error + * + */ + DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vUserFk); + + IF(account.user_hasRole(vWorkerName,'coolerBoss')) + THEN + INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) + VALUES(vWorkerFk, vWorkerMistakeTypeFk); + ELSE + CALL util.throw('No tienes permisos para realizar la acción'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72715,28 +72719,28 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerShelving_Add`(vWorkerFk INT, vBarcode VARCHAR(12)) -BEGIN -/* - * Inserta en workerShelving asociando los carros al trabajador - * @Param vWorkerFk es id del trabajador - * @Param vBarcode se puede pasar tanto el smarttag como el shelving - */ - DECLARE vIsShelvingFk BOOL; - - SELECT COUNT(*) > 0 INTO vIsShelvingFk - FROM vn.shelving s - WHERE s.code = vBarcode COLLATE utf8_general_ci; - - IF NOT vIsShelvingFk THEN - - SELECT st.shelvingFk INTO vBarcode - FROM vn.smartTag st - WHERE st.code = vBarcode COLLATE utf8_general_ci; - - END IF; - - INSERT INTO vn.workerShelving (workerFk, shelvingFk) - VALUES(vWorkerFk, vBarcode); +BEGIN +/* + * Inserta en workerShelving asociando los carros al trabajador + * @Param vWorkerFk es id del trabajador + * @Param vBarcode se puede pasar tanto el smarttag como el shelving + */ + DECLARE vIsShelvingFk BOOL; + + SELECT COUNT(*) > 0 INTO vIsShelvingFk + FROM vn.shelving s + WHERE s.code = vBarcode COLLATE utf8_general_ci; + + IF NOT vIsShelvingFk THEN + + SELECT st.shelvingFk INTO vBarcode + FROM vn.smartTag st + WHERE st.code = vBarcode COLLATE utf8_general_ci; + + END IF; + + INSERT INTO vn.workerShelving (workerFk, shelvingFk) + VALUES(vWorkerFk, vBarcode); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72754,32 +72758,32 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerShelving_delete`(vWorkerFk INT, vBarcode VARCHAR(12)) -BEGIN -/* - * Borra de workerShelving el carro o etiqueta insertado por el trabajador - * @param vWorkerFk es id del trabajador - * @param vBarcode se puede pasar tanto el smarttag como el shelving - */ - DECLARE vIsShelvingFk BOOL; - - - SELECT COUNT(*) > 0 INTO vIsShelvingFk - FROM vn.shelving s - WHERE s.code = vBarcode COLLATE utf8_general_ci; - - - IF NOT vIsShelvingFk THEN - - SELECT st.shelvingFk INTO vBarcode - FROM vn.smartTag st - WHERE st.code = vBarcode COLLATE utf8_general_ci; - - END IF; - - DELETE FROM vn.workerShelving - WHERE shelvingFk = vBarcode COLLATE utf8_general_ci - AND workerFk = vWorkerFk ; - +BEGIN +/* + * Borra de workerShelving el carro o etiqueta insertado por el trabajador + * @param vWorkerFk es id del trabajador + * @param vBarcode se puede pasar tanto el smarttag como el shelving + */ + DECLARE vIsShelvingFk BOOL; + + + SELECT COUNT(*) > 0 INTO vIsShelvingFk + FROM vn.shelving s + WHERE s.code = vBarcode COLLATE utf8_general_ci; + + + IF NOT vIsShelvingFk THEN + + SELECT st.shelvingFk INTO vBarcode + FROM vn.smartTag st + WHERE st.code = vBarcode COLLATE utf8_general_ci; + + END IF; + + DELETE FROM vn.workerShelving + WHERE shelvingFk = vBarcode COLLATE utf8_general_ci + AND workerFk = vWorkerFk ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72801,11 +72805,11 @@ BEGIN /*INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk) VALUES(vUserFk, vDated, FALSE, vWarehouseFk); - + CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/ - + CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,util.VN_NOW(),FALSE); - + END ;; DELIMITER ; @@ -72831,8 +72835,8 @@ BEGIN * */ - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72909,13 +72913,13 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE) BEGIN SET @order := 0; - - UPDATE workerTimeControl - SET `order` = @order := @order + 1 - WHERE vUserFk =userFk + + UPDATE workerTimeControl + SET `order` = @order := @order + 1 + WHERE vUserFk =userFk AND vDated = DATE(timed) ORDER BY timed; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72934,8 +72938,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - - + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; @@ -73024,73 +73028,73 @@ proc: BEGIN DECLARE vTo VARCHAR(50) DEFAULT NULL; DECLARE vUserName VARCHAR(50) DEFAULT NULL; DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax FROM workerTimeControlParams; SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in'; - + SELECT MAX(timed) INTO vLastOut - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'out'; SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo FROM account.user u - WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); - + WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); + SELECT CONCAT(firstName,' ',lastName) INTO vUserName FROM worker w WHERE w.id = vUserFk; IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + + -- VERIFICAR DESCANSO DIARIO + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; - END IF; - + END IF; + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM workerTimeControl + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM workerTimeControl WHERE userFk = vUserFk AND timed >= vLastIn - ) THEN + ) THEN SELECT "Dias con fichadas impares" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; - + -- VERIFICAR VACACIONES SELECT at2.name INTO vCalendarStateType - FROM calendar c + FROM calendar c JOIN business b ON b.id = c.businessFk JOIN absenceType at2 ON at2.id = c.dayOffTypeFk WHERE c.dated = util.VN_CURDATE() AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; - + -- VERIFICAR CONTRATO EN VIGOR IF (SELECT COUNT(*) FROM business b @@ -73102,44 +73106,44 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); - + SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); + DROP TEMPORARY TABLE IF EXISTS tmp.trash; CREATE TEMPORARY TABLE tmp.trash SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl + FROM workerTimeControl WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND) AND userFk= vUserFk AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; - - DROP TEMPORARY TABLE tmp.trash; - ELSE -- DIA ACTUAL - + DROP TEMPORARY TABLE tmp.trash; + + ELSE -- DIA ACTUAL + -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked + SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed >= vLastIn ORDER BY timed; - IF vTimedWorked > vDayWorkMax THEN + IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; @@ -73162,10 +73166,10 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; END IF;*/ - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73185,7 +73189,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_checkBreak`(vStarted DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas * El sistema verificará el descanso corto en la siguiente semana * o el largo en las 2 siguientes semanas a partir de la fecha dada * @param vStarted día inicio de la semana en el que se quiere verificar @@ -73196,27 +73200,27 @@ BEGIN DECLARE vShortWeekBreak INT; DECLARE vLongWeekBreak INT; - SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), + SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)), - shortWeekBreak, + shortWeekBreak, longWeekBreak INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak FROM workerTimeControlConfig; - + SET @previousTimed:= UNIX_TIMESTAMP(vStarted); SET @lastUserFk := NULL; - + -- Descanso corto en la semana - + DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT DISTINCT userFk workerFk - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out'); - + DROP TEMPORARY TABLE IF EXISTS tmp.worker2; CREATE TEMPORARY TABLE tmp.worker2 (PRIMARY KEY(workerFk)) @@ -73229,28 +73233,28 @@ BEGIN SELECT sub2.userFk workerFk FROM(SELECT sub.userFk, IF(sub.userFk <> @lastUserFk, - @previousTimed:= sub.timed, + @previousTimed:= sub.timed, FALSE), - IF(sub.timed - @previousTimed >= vShortWeekBreak, - TRUE, + IF(sub.timed - @previousTimed >= vShortWeekBreak, + TRUE, FALSE) hasShortWeekBreak, @previousTimed:= sub.timed, @lastUserFk:= sub.userFk FROM ( SELECT userFk, UNIX_TIMESTAMP(timed) timed - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, UNIX_TIMESTAMP(IFNULL( - MIN(wtc.timed), + MIN(wtc.timed), DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN vShortEnded - AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN vShortEnded + AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) GROUP BY w.workerFk UNION SELECT w.workerFk, @@ -73258,10 +73262,10 @@ BEGIN MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN - DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN + DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -73271,7 +73275,7 @@ BEGIN GROUP BY sub2.userFk HAVING NOT SUM(hasShortWeekBreak); - -- Descanso largo en las 2 siguientes semanas + -- Descanso largo en las 2 siguientes semanas DROP TEMPORARY TABLE tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) @@ -73291,12 +73295,12 @@ BEGIN (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT sub2.userFk workerFk - FROM(SELECT userFk, + FROM(SELECT userFk, IF(userFk <> @lastUserFk, - @previousTimed:= timed, + @previousTimed:= timed, TRUE), - IF(timed - @previousTimed >= vLongWeekBreak, - TRUE, + IF(timed - @previousTimed >= vLongWeekBreak, + TRUE, FALSE) hasLongWeekBreak, @previousTimed:= timed, @lastUserFk:= userFk @@ -73305,24 +73309,24 @@ BEGIN JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk WHERE timed BETWEEN vStarted AND vLongEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), + UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN vLongEnded - AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN vLongEnded + AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) GROUP BY w.workerFk UNION - SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), + SELECT w.workerFk, + UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -73349,334 +73353,334 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_clockIn`( - vWorker INT, - vTimed DATETIME, +CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_clockIn`( + vWorker INT, + vTimed DATETIME, vDirection VARCHAR(10)) -BEGIN -/** - * Verifica si el empleado puede fichar - * @param vWorker Identificador del trabajador - * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = util.VN_NOW() - * @param vDirection solo se pueden pasa los valores del campo - * workerTimeControl.direction ENUM('in', 'out', 'middle') - * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. - * Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario - * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá - * fichada a la tabla vn.workerTimeControl - */ - DECLARE vLastIn DATETIME; - DECLARE vLastOut DATETIME; - DECLARE vNextIn DATETIME; - DECLARE vLastDirection VARCHAR(6); - DECLARE vNextDirection VARCHAR(6); - DECLARE vDayBreak INT; - DECLARE vShortWeekBreak INT; - DECLARE vLongWeekBreak INT; - DECLARE vWeekScope INT; - DECLARE vGap INT; - DECLARE vMailTo VARCHAR(50) DEFAULT NULL; - DECLARE vUserName VARCHAR(50) DEFAULT NULL; - DECLARE vIsError BOOLEAN DEFAULT FALSE; - DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL; - DECLARE vErrorCode VARCHAR(50); - DECLARE vDated DATE; - DECLARE vIsAllowedToWork VARCHAR(50); - DECLARE vDepartmentFk INT; - DECLARE vTimedLoop BIGINT; - DECLARE vTimedLoopPrevious BIGINT; - DECLARE vHasBreakWeek BOOLEAN DEFAULT FALSE; - DECLARE vManual BOOLEAN DEFAULT TRUE; - DECLARE vDone INT DEFAULT FALSE; - - DECLARE vCursor CURSOR FOR - SELECT UNIX_TIMESTAMP(vTimed) timed - UNION - SELECT UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed BETWEEN (vTimed - INTERVAL vGap SECOND) AND vTimed - AND userFk = vWorker - AND direction IN ('in', 'out') - ORDER BY timed ASC; - - DECLARE vCursor2 CURSOR FOR - SELECT UNIX_TIMESTAMP(vTimed) timed - UNION - SELECT UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed BETWEEN vTimed AND (vTimed + INTERVAL vGap SECOND) - AND userFk = vWorker - AND direction IN ('in', 'out') - ORDER BY timed ASC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - - SELECT CONCAT(u.name, '@verdnatura.es'), - CONCAT(w.firstName, ' ', w.lastName) - INTO vMailTo, vUserName - FROM account.user u - JOIN worker w ON w.bossFk = u.id - WHERE w.id = vWorker; - - CASE vErrorCode - WHEN 'IS_NOT_ALLOWED_FUTURE' THEN - SELECT 'No se permite fichar a futuro' INTO vErrorMessage; - WHEN 'INACTIVE_BUSINESS' THEN - SELECT 'No hay un contrato en vigor' INTO vErrorMessage; - WHEN 'IS_NOT_ALLOWED_WORK' THEN - SELECT 'No está permitido trabajar' INTO vErrorMessage; - WHEN 'ODD_WORKERTIMECONTROL' THEN - SELECT 'Fichadas impares' INTO vErrorMessage; - WHEN 'BREAK_DAY' THEN - SELECT CONCAT('Descanso diario ', FORMAT(vDayBreak/3600, 0), 'h.') - INTO vErrorMessage; - WHEN 'BREAK_WEEK' THEN - SELECT CONCAT('Descanso semanal ', - FORMAT(vShortWeekBreak / 3600,0) ,'h. / ', - FORMAT(vLongWeekBreak / 3600, 0) ,'h.') INTO vErrorMessage; - WHEN 'WRONG_DIRECTION' THEN - SELECT 'Dirección incorrecta' INTO vErrorMessage; - ELSE - SELECT 'Error sin definir'INTO vErrorMessage; - END CASE; - - SELECT vErrorMessage `error`; - SELECT CONCAT(vUserName, - ' no ha podido fichar por el siguiente problema: ', - vErrorMessage) - INTO vErrorMessage; - CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); - - END; - - IF (vTimed IS NULL) THEN - SET vTimed = util.VN_NOW(); - SET vManual = FALSE; - END IF; - - SET vDated = DATE(vTimed); - - SELECT IF(pc.category_name = 'Conductor +3500kg', - wc.dayBreakDriver, - wc.dayBreak), - wc.shortWeekBreak, - wc.longWeekBreak, - wc.weekScope - INTO vDayBreak, - vShortWeekBreak, - vLongWeekBreak, - vWeekScope - FROM business b - JOIN postgresql.professional_category pc - ON pc.professional_category_id = b.workerBusinessProfessionalCategoryFk - JOIN workerTimeControlConfig wc ON TRUE - WHERE b.workerFk = vWorker - AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated); - - SELECT timed INTO vLastIn - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'in' - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - SELECT timed INTO vLastOut - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'out' - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - SELECT timed INTO vNextIn - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'in' - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT direction INTO vNextDirection - FROM workerTimeControl - WHERE userFk = vWorker - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT direction INTO vLastDirection - FROM workerTimeControl - WHERE userFk = vWorker - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - -- FICHADAS A FUTURO - IF vTimed > DATE_ADD(util.VN_NOW(), INTERVAL 60 SECOND) THEN - SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; - CALL util.throw(vErrorCode); - END IF; - - -- CONTRATO EN VIGOR - IF vDayBreak IS NULL THEN - SET vErrorCode = 'INACTIVE_BUSINESS'; - CALL util.throw(vErrorCode); - END IF; - - -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR - CALL timeBusiness_calculateByWorker(vWorker, vDated, vDated); - SELECT isAllowedToWork INTO vIsAllowedToWork - FROM tmp.timeBusinessCalculate; - DROP TEMPORARY TABLE tmp.timeBusinessCalculate; - - IF NOT vIsAllowedToWork THEN - SET vErrorCode = 'IS_NOT_ALLOWED_WORK'; - CALL util.throw(vErrorCode); - END IF; - - -- DIRECCION CORRECTA - CALL workerTimeControl_direction(vWorker, vTimed); - IF (SELECT - IF(IF(option1 IN ('inMiddle', 'outMiddle'), - 'middle', - option1) <> vDirection - AND IF(option2 IN ('inMiddle', 'outMiddle'), - 'middle', - IFNULL(option2, '')) <> vDirection, - TRUE , - FALSE) - FROM tmp.workerTimeControlDirection - ) THEN - SET vIsError = TRUE; - END IF; - - DROP TEMPORARY TABLE tmp.workerTimeControlDirection; - IF vIsError = TRUE THEN - SET vErrorCode = 'WRONG_DIRECTION'; - CALL util.throw(vErrorCode); - END IF; - - -- FICHADAS IMPARES - IF (SELECT IF(vDirection = 'in', - MOD(COUNT(*), 2) , - IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) - FROM workerTimeControl - WHERE userFk = vWorker - AND timed BETWEEN vLastIn AND vTimed - ) THEN - SET vErrorCode = 'ODD_WORKERTIMECONTROL'; - CALL util.throw(vErrorCode); - END IF; - - -- DESCANSO DIARIO - CASE vDirection - WHEN 'in' THEN - IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN - SET vIsError = TRUE; - END IF; - WHEN 'out' THEN - IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN - SET vIsError = TRUE; - END IF; - ELSE BEGIN END; - END CASE; - - IF vIsError THEN - SET vErrorCode = 'BREAK_DAY'; - CALL util.throw(vErrorCode); - END IF; - - -- VERIFICAR DESCANSO SEMANAL - IF (vDirection IN('in', 'out')) THEN - -- VERIFICA DESCANSO CORTO EN LA ÚLTIMA SEMANA - SET vGap = vWeekScope; - SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - -- VERIFICA DESCANSO LARGO EN LA ÚLTIMAS 2 SEMANAS - IF NOT vHasBreakWeek THEN - SET vGap = vWeekScope * 2; - SET vTimedLoopPrevious = UNIX_TIMESTAMP(vTimed - INTERVAL vGap SECOND); - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vLongWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - END IF; - - IF vManual THEN - -- VERIFICA DESCANSO CORTO EN LA PRÓXIMA SEMANA - SET vGap = vWeekScope; - SET vTimedLoopPrevious = vTimed; - SET vDone = FALSE; - OPEN vCursor2; - l:LOOP - FETCH vCursor2 INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor2; - -- VERIFICA DESCANSO LARGO EN LAS PRÓXIMAS 2 SEMANAS - IF NOT vHasBreakWeek THEN - SET vGap = vWeekScope * 2; - SET vTimedLoopPrevious = vTimed; - SET vDone = FALSE; - OPEN vCursor2; - l:LOOP - FETCH vCursor2 INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor2; - END IF; - END IF; - IF NOT vHasBreakWeek THEN - SET vErrorCode = 'BREAK_WEEK'; - CALL util.throw(vErrorCode); - END IF; - END IF; - - -- SE PERMITE FICHAR - INSERT INTO workerTimeControl(userFk, timed, direction, manual) - VALUES(vWorker, vTimed, vDirection, vManual); - - SELECT LAST_INSERT_ID() id; +BEGIN +/** + * Verifica si el empleado puede fichar + * @param vWorker Identificador del trabajador + * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = util.VN_NOW() + * @param vDirection solo se pueden pasa los valores del campo + * workerTimeControl.direction ENUM('in', 'out', 'middle') + * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. + * Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario + * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá + * fichada a la tabla vn.workerTimeControl + */ + DECLARE vLastIn DATETIME; + DECLARE vLastOut DATETIME; + DECLARE vNextIn DATETIME; + DECLARE vLastDirection VARCHAR(6); + DECLARE vNextDirection VARCHAR(6); + DECLARE vDayBreak INT; + DECLARE vShortWeekBreak INT; + DECLARE vLongWeekBreak INT; + DECLARE vWeekScope INT; + DECLARE vGap INT; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vIsError BOOLEAN DEFAULT FALSE; + DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL; + DECLARE vErrorCode VARCHAR(50); + DECLARE vDated DATE; + DECLARE vIsAllowedToWork VARCHAR(50); + DECLARE vDepartmentFk INT; + DECLARE vTimedLoop BIGINT; + DECLARE vTimedLoopPrevious BIGINT; + DECLARE vHasBreakWeek BOOLEAN DEFAULT FALSE; + DECLARE vManual BOOLEAN DEFAULT TRUE; + DECLARE vDone INT DEFAULT FALSE; + + DECLARE vCursor CURSOR FOR + SELECT UNIX_TIMESTAMP(vTimed) timed + UNION + SELECT UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed BETWEEN (vTimed - INTERVAL vGap SECOND) AND vTimed + AND userFk = vWorker + AND direction IN ('in', 'out') + ORDER BY timed ASC; + + DECLARE vCursor2 CURSOR FOR + SELECT UNIX_TIMESTAMP(vTimed) timed + UNION + SELECT UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed BETWEEN vTimed AND (vTimed + INTERVAL vGap SECOND) + AND userFk = vWorker + AND direction IN ('in', 'out') + ORDER BY timed ASC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + + SELECT CONCAT(u.name, '@verdnatura.es'), + CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorker; + + CASE vErrorCode + WHEN 'IS_NOT_ALLOWED_FUTURE' THEN + SELECT 'No se permite fichar a futuro' INTO vErrorMessage; + WHEN 'INACTIVE_BUSINESS' THEN + SELECT 'No hay un contrato en vigor' INTO vErrorMessage; + WHEN 'IS_NOT_ALLOWED_WORK' THEN + SELECT 'No está permitido trabajar' INTO vErrorMessage; + WHEN 'ODD_WORKERTIMECONTROL' THEN + SELECT 'Fichadas impares' INTO vErrorMessage; + WHEN 'BREAK_DAY' THEN + SELECT CONCAT('Descanso diario ', FORMAT(vDayBreak/3600, 0), 'h.') + INTO vErrorMessage; + WHEN 'BREAK_WEEK' THEN + SELECT CONCAT('Descanso semanal ', + FORMAT(vShortWeekBreak / 3600,0) ,'h. / ', + FORMAT(vLongWeekBreak / 3600, 0) ,'h.') INTO vErrorMessage; + WHEN 'WRONG_DIRECTION' THEN + SELECT 'Dirección incorrecta' INTO vErrorMessage; + ELSE + SELECT 'Error sin definir'INTO vErrorMessage; + END CASE; + + SELECT vErrorMessage `error`; + SELECT CONCAT(vUserName, + ' no ha podido fichar por el siguiente problema: ', + vErrorMessage) + INTO vErrorMessage; + CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); + + END; + + IF (vTimed IS NULL) THEN + SET vTimed = util.VN_NOW(); + SET vManual = FALSE; + END IF; + + SET vDated = DATE(vTimed); + + SELECT IF(pc.category_name = 'Conductor +3500kg', + wc.dayBreakDriver, + wc.dayBreak), + wc.shortWeekBreak, + wc.longWeekBreak, + wc.weekScope + INTO vDayBreak, + vShortWeekBreak, + vLongWeekBreak, + vWeekScope + FROM business b + JOIN postgresql.professional_category pc + ON pc.professional_category_id = b.workerBusinessProfessionalCategoryFk + JOIN workerTimeControlConfig wc ON TRUE + WHERE b.workerFk = vWorker + AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated); + + SELECT timed INTO vLastIn + FROM workerTimeControl + WHERE userFk = vWorker + AND direction = 'in' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vLastOut + FROM workerTimeControl + WHERE userFk = vWorker + AND direction = 'out' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vNextIn + FROM workerTimeControl + WHERE userFk = vWorker + AND direction = 'in' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vNextDirection + FROM workerTimeControl + WHERE userFk = vWorker + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vLastDirection + FROM workerTimeControl + WHERE userFk = vWorker + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + -- FICHADAS A FUTURO + IF vTimed > DATE_ADD(util.VN_NOW(), INTERVAL 60 SECOND) THEN + SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; + CALL util.throw(vErrorCode); + END IF; + + -- CONTRATO EN VIGOR + IF vDayBreak IS NULL THEN + SET vErrorCode = 'INACTIVE_BUSINESS'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR + CALL timeBusiness_calculateByWorker(vWorker, vDated, vDated); + SELECT isAllowedToWork INTO vIsAllowedToWork + FROM tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE tmp.timeBusinessCalculate; + + IF NOT vIsAllowedToWork THEN + SET vErrorCode = 'IS_NOT_ALLOWED_WORK'; + CALL util.throw(vErrorCode); + END IF; + + -- DIRECCION CORRECTA + CALL workerTimeControl_direction(vWorker, vTimed); + IF (SELECT + IF(IF(option1 IN ('inMiddle', 'outMiddle'), + 'middle', + option1) <> vDirection + AND IF(option2 IN ('inMiddle', 'outMiddle'), + 'middle', + IFNULL(option2, '')) <> vDirection, + TRUE , + FALSE) + FROM tmp.workerTimeControlDirection + ) THEN + SET vIsError = TRUE; + END IF; + + DROP TEMPORARY TABLE tmp.workerTimeControlDirection; + IF vIsError = TRUE THEN + SET vErrorCode = 'WRONG_DIRECTION'; + CALL util.throw(vErrorCode); + END IF; + + -- FICHADAS IMPARES + IF (SELECT IF(vDirection = 'in', + MOD(COUNT(*), 2) , + IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) + FROM workerTimeControl + WHERE userFk = vWorker + AND timed BETWEEN vLastIn AND vTimed + ) THEN + SET vErrorCode = 'ODD_WORKERTIMECONTROL'; + CALL util.throw(vErrorCode); + END IF; + + -- DESCANSO DIARIO + CASE vDirection + WHEN 'in' THEN + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + WHEN 'out' THEN + IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + ELSE BEGIN END; + END CASE; + + IF vIsError THEN + SET vErrorCode = 'BREAK_DAY'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICAR DESCANSO SEMANAL + IF (vDirection IN('in', 'out')) THEN + -- VERIFICA DESCANSO CORTO EN LA ÚLTIMA SEMANA + SET vGap = vWeekScope; + SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); + SET vDone = FALSE; + OPEN vCursor; + l:LOOP + FETCH vCursor INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor; + -- VERIFICA DESCANSO LARGO EN LA ÚLTIMAS 2 SEMANAS + IF NOT vHasBreakWeek THEN + SET vGap = vWeekScope * 2; + SET vTimedLoopPrevious = UNIX_TIMESTAMP(vTimed - INTERVAL vGap SECOND); + SET vDone = FALSE; + OPEN vCursor; + l:LOOP + FETCH vCursor INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vLongWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor; + END IF; + + IF vManual THEN + -- VERIFICA DESCANSO CORTO EN LA PRÓXIMA SEMANA + SET vGap = vWeekScope; + SET vTimedLoopPrevious = vTimed; + SET vDone = FALSE; + OPEN vCursor2; + l:LOOP + FETCH vCursor2 INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor2; + -- VERIFICA DESCANSO LARGO EN LAS PRÓXIMAS 2 SEMANAS + IF NOT vHasBreakWeek THEN + SET vGap = vWeekScope * 2; + SET vTimedLoopPrevious = vTimed; + SET vDone = FALSE; + OPEN vCursor2; + l:LOOP + FETCH vCursor2 INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor2; + END IF; + END IF; + IF NOT vHasBreakWeek THEN + SET vErrorCode = 'BREAK_WEEK'; + CALL util.throw(vErrorCode); + END IF; + END IF; + + -- SE PERMITE FICHAR + INSERT INTO workerTimeControl(userFk, timed, direction, manual) + VALUES(vWorker, vTimed, vDirection, vManual); + + SELECT LAST_INSERT_ID() id; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73699,27 +73703,27 @@ BEGIN * Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada * @param vWorkerFk Identificador del trabajador * @return (option1, option2) - * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') + * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; - IF (vTimed IS NULL) THEN + IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); END IF; - + SELECT timed INTO vLastIn - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'in' + AND direction = 'in' AND timed < vTimed ORDER BY timed DESC LIMIT 1; - + SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'middle' + AND direction = 'middle' AND timed BETWEEN vLastIn AND util.VN_NOW(); DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection; @@ -73768,7 +73772,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`( - vUserFk INT, + vUserFk INT, vDated DATE) BEGIN /** @@ -73778,9 +73782,9 @@ BEGIN * @param vDated Fecha proporcionada */ CALL timeControl_calculateByWorker( - vUserFk, + vUserFk, DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated)); - + SET @position := 0; SET @lastDated := NULL; @@ -73797,7 +73801,7 @@ BEGIN MAX(2daysAgoDirection) 2daysAgoDirection, MAX(1daysAgo) 1daysAgo, MAX(1daysAgoDirection) 1daysAgoDirection, - MAX(0daysAgo) 0daysAgo, + MAX(0daysAgo) 0daysAgo, MAX(0daysAgoDirection) 0daysAgoDirection FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo, IF(daysAgo = 5, timed, '') 5daysAgo, @@ -73817,7 +73821,7 @@ BEGIN direction, position FROM(SELECT DATEDIFF(vDated, timed) daysAgo, - TIME_FORMAT(timed,'%H:%i') timed, + TIME_FORMAT(timed,'%H:%i') timed, IF(DATE(timed) <> @lastDated, @position := 0, NULL), @position := @position+1 position, @lastDated := DATE(timed), @@ -73829,18 +73833,18 @@ BEGIN LIMIT 10000000000000000000 )sub )sub2 - GROUP BY position) sub3 + GROUP BY position) sub3 JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal, MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal, MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal, MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal, MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal, MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal, - MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal + MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal FROM (SELECT DATEDIFF(vDated, dated) daysAgo, timeWorkSeconds FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE; - + DROP TEMPORARY TABLE tmp.timeControlCalculate; END ;; DELIMITER ; @@ -73904,45 +73908,45 @@ BEGIN DECLARE vDirectionPrevious VARCHAR(6); DECLARE vTimedPrevious DATETIME; - SELECT direction INTO vDirectionRemove - FROM vn.workerTimeControl - WHERE userFk = vUserFk + SELECT direction INTO vDirectionRemove + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed = vTimed ; IF vDirectionRemove = 'out' THEN - + SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - + LIMIT 1; + IF vDirectionPrevious = "middle" THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "out" WHERE userFk = vUserFk AND timed = vTimedPrevious; END IF; - + ELSE IF vDirectionRemove = 'in' THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "in" WHERE userFk = vUserFk AND timed > vTimed ORDER BY timed ASC - LIMIT 1; + LIMIT 1; END IF; - + END IF; - + DELETE FROM vn.workerTimeControl - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed = vTimed; - + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73970,31 +73974,31 @@ proc: BEGIN UPDATE vn.workerTimeControl SET direction = 'middle'; /*2- poner los out*/ -UPDATE vn.workerTimeControl wtc - JOIN +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MAX(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "out" - WHERE wtc.userFk = sub.userFk + WHERE wtc.userFk = sub.userFk AND wtc.timed = sub.maxTimed; - - /*3- poner los in*/ -UPDATE vn.workerTimeControl wtc - JOIN + + /*3- poner los in*/ +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MIN(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "in" - WHERE wtc.userFk = sub.userFk - AND wtc.timed = sub.maxTimed ; - + WHERE wtc.userFk = sub.userFk + AND wtc.timed = sub.maxTimed ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74014,11 +74018,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_sendMail`(vWeek INT, vYear INT, vWorkerFk INT) BEGIN /** - * Inserta en la tabla vn.mail para notificar a los empleados que teletrabajan de las jornadas que se han registrado. + * Inserta en la tabla vn.mail para notificar a los empleados que teletrabajan de las jornadas que se han registrado. * Inserta fichadas en el casos que se determina que el empleado está realizando teletrabajo * - * @param vWeek - * @param vYear + * @param vWeek + * @param vYear * @param vWorkerFk -> En el caso de querer generarlo para todos los empleados deberá de informarse como NULL */ DECLARE vStarted VARCHAR(25); @@ -74048,20 +74052,20 @@ BEGIN DECLARE vError BOOL DEFAULT FALSE; DECLARE vCursor CURSOR FOR - SELECT CONCAT(u.name, '@verdnatura.es'), - u.id, - tb.dated, - tb.timeWorkDecimal, - LEFT(tb.timeWorkSexagesimal,5) timeWorkSexagesimal, - tb.timeTable, - tc.timeWorkDecimal timeWorkedDecimal, - LEFT(tc.timeWorkSexagesimal,5) timeWorkedSexagesimal, - tb.type, + SELECT CONCAT(u.name, '@verdnatura.es'), + u.id, + tb.dated, + tb.timeWorkDecimal, + LEFT(tb.timeWorkSexagesimal,5) timeWorkSexagesimal, + tb.timeTable, + tc.timeWorkDecimal timeWorkedDecimal, + LEFT(tc.timeWorkSexagesimal,5) timeWorkedSexagesimal, + tb.type, tb.businessFk, - tb.permissionRate, + tb.permissionRate, d.isTeleworking FROM tmp.timeBusinessCalculate tb - JOIN account.user u ON u.id = tb.userFk + JOIN account.user u ON u.id = tb.userFk JOIN department d ON d.id = tb.departmentFk JOIN business b ON b.id = tb.businessFk LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated @@ -74069,29 +74073,29 @@ BEGIN LEFT JOIN account.`user` u2 ON u2.id = w.bossFk JOIN (SELECT tb.userFk, SUM(IF(tb.type IS NULL, - IF(tc.timeWorkDecimal > 0, FALSE, IF(tb.timeWorkDecimal > 0, TRUE, FALSE)), + IF(tc.timeWorkDecimal > 0, FALSE, IF(tb.timeWorkDecimal > 0, TRUE, FALSE)), TRUE))isTeleworkingWeek FROM tmp.timeBusinessCalculate1 tb LEFT JOIN tmp.timeControlCalculate1 tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated GROUP BY tb.userFk HAVING isTeleworkingWeek > 0 )sub ON sub.userFk = u.id - WHERE d.hasToRefill + WHERE d.hasToRefill AND IFNULL(vWorkerFk, u.id) = u.id - AND b.companyCodeFk = 'VNL' - AND w.businessFk - ORDER BY u.id, tb.dated; + AND b.companyCodeFk = 'VNL' + AND w.businessFk + ORDER BY u.id, tb.dated; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN SET vError = TRUE; - + INSERT INTO tmp.error(workerFk) SELECT vWorkerFk; END; - + DROP TABLE IF EXISTS tmp.timeControlCalculate; DROP TABLE IF EXISTS tmp.timeBusinessCalculate; DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; @@ -74103,24 +74107,24 @@ BEGIN CREATE TEMPORARY TABLE tmp.error (workerFk INT); SELECT CONCAT (MIN(dated), ' 00:00:00'), CONCAT (MAX(dated), ' 23:59:59') INTO vStarted, vEnded - FROM time - WHERE year = vYear AND + FROM time + WHERE year = vYear AND week = vWeek; - DELETE FROM workerTimeControl + DELETE FROM workerTimeControl WHERE IFNULL(vWorkerFk, userFk) = userFk AND - timed BETWEEN vStarted AND vEnded AND + timed BETWEEN vStarted AND vEnded AND isSendMail; UPDATE workerTimeControlMail SET updated = util.VN_NOW(), state = 'SENDED' - WHERE year = vYear AND + WHERE year = vYear AND week = vWeek AND IFNULL(vWorkerFk, workerFk) = workerFk ; IF vWorkerFk IS NULL THEN CALL timeControl_calculateAll(vStarted,vEnded); - CALL timeBusiness_calculateAll(vStarted,vEnded); + CALL timeBusiness_calculateAll(vStarted,vEnded); ELSE CALL timeControl_calculateByUser(vWorkerFk,vStarted,vEnded); CALL timeBusiness_calculateByUser(vWorkerFk,vStarted,vEnded); @@ -74142,12 +74146,12 @@ proc: LOOP IF vDone THEN LEAVE proc; END IF; - + START TRANSACTION; SET vError = FALSE; IF vTimeWorkDecimal>0 AND vTimeWorkedDecimal IS NULL AND IFNULL(vPermissionRate, TRUE) THEN - IF vTimeTable IS NULL THEN + IF vTimeTable IS NULL THEN INSERT INTO workerTimeControl (userFk, timed, manual, direction, isSendMail) SELECT vWorkerFk, CONCAT(vDated,' 08:00'), TRUE, 'in', TRUE; IF vTimeWorkDecimal >= 5 THEN @@ -74160,63 +74164,63 @@ proc: LOOP SELECT vWorkerFk,CONCAT(vDated,' ', LEFT (SEC_TO_TIME(28800 + (vTimeWorkDecimal * 3600)), 5)), TRUE, 'out', TRUE; ELSE SELECT SUM(TIME_TO_SEC(j.end)-TIME_TO_SEC(j.start))/3600 INTO vTimeTableDecimal - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND - j.day_id = WEEKDAY(vDated)+1; + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; IF vTimeWorkDecimal = vTimeTableDecimal THEN INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) SELECT vWorkerFk, CONCAT(vDated, ' ', j.start), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND j.day_id = WEEKDAY(vDated)+1; - + INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) SELECT vWorkerFk, CONCAT(vDated, ' ', j.end), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND - j.day_id = WEEKDAY(vDated)+1; + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; ELSE INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) SELECT vWorkerFk, CONCAT(vDated, ' ', MIN(j.start)), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND - j.day_id = WEEKDAY(vDated)+1; + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + (vTimeWorkDecimal * 3600))), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND - j.day_id = WEEKDAY(vDated)+1; - END IF; - + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; + END IF; + IF vTimeWorkDecimal >= 5 THEN INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + 3600)), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND - j.day_id = WEEKDAY(vDated)+1; + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; INSERT INTO workerTimeControl (userFk, timed, manual, isSendMail) SELECT vWorkerFk, CONCAT(vDated, ' ', SEC_TO_TIME(TIME_TO_SEC(MIN(j.start)) + 4800)), TRUE, TRUE - FROM postgresql.journey j - WHERE j.business_id = vBusinessFk AND - j.day_id = WEEKDAY(vDated)+1; + FROM postgresql.journey j + WHERE j.business_id = vBusinessFk AND + j.day_id = WEEKDAY(vDated)+1; END IF; - + UPDATE workerTimeControl wtc - JOIN (SELECT id FROM workerTimeControl - WHERE userFk = vWorkerFk AND + JOIN (SELECT id FROM workerTimeControl + WHERE userFk = vWorkerFk AND timed BETWEEN vDated AND CONCAT(vDated, ' 23:59:59') ORDER BY timed ASC LIMIT 1)sub on sub.id= wtc.id - SET direction = 'in' ; - + SET direction = 'in' ; + UPDATE workerTimeControl wtc - JOIN (SELECT id FROM workerTimeControl - WHERE userFk = vWorkerFk AND + JOIN (SELECT id FROM workerTimeControl + WHERE userFk = vWorkerFk AND timed BETWEEN vDated AND CONCAT(vDated, ' 23:59:59') - ORDER BY timed DESC + ORDER BY timed DESC LIMIT 1)sub on sub.id= wtc.id - SET direction = 'out' ; - + SET direction = 'out' ; + END IF; END IF; @@ -74235,27 +74239,27 @@ proc: LOOP ", IFNULL(vAbsenceType, IF (vTimeWorkedDecimal>0, "Presencial", IF(vTimeWorkDecimal>0, "Teletrabajo", " - "))), " ", IFNULL(vTimeWorkedSexagesimal,IF(IFNULL(vPermissionRate, TRUE), vTimeWorkDecimal, 0)), " ") INTO vBody - FROM workerTimeControl - WHERE userFk = vWorkerFk AND + FROM workerTimeControl + WHERE userFk = vWorkerFk AND timed BETWEEN vDated AND CONCAT(vDated," 23:59:59"); SET vTimeWorkDecimalTotal = vTimeWorkDecimalTotal + IFNULL(vTimeWorkedDecimal, IF( IFNULL(vPermissionRate, TRUE), vTimeWorkDecimal, 0)); SET vDone = FALSE; FETCH vCursor INTO vReceiver, vWorkerFk, vDated, vTimeWorkDecimal, vTimeWorkSexagesimal, vTimeTable, vTimeWorkedDecimal, vTimeWorkedSexagesimal, vAbsenceType, vBusinessFk, vPermissionRate, vIsTeleworking; - IF vWorkerFk <> vWorkerFkOld OR vDone THEN + IF vWorkerFk <> vWorkerFkOld OR vDone THEN SELECT CONCAT_WS(' ', fi, firstName, lastName) INTO vWorkerInfo FROM worker WHERE id = vWorkerFkOld; SET vHeader = CONCAT("


-

", vWorkerInfo , "

+

", vWorkerInfo , "

@@ -74278,15 +74282,15 @@ proc: LOOP IF vIsTeleworkingOld AND NOT vError THEN CALL mail_insert( - vReceiverOld, + vReceiverOld, 'timecontrol@verdnatura.es', - CONCAT('Registro de horas semana ', vWeek, ' año ', vYear) , + CONCAT('Registro de horas semana ', vWeek, ' año ', vYear) , CONCAT(vHeader, ' ' , vBody, ' ', vFooter) ); INSERT IGNORE INTO workerTimeControlMail (workerFk, year, week) VALUES(vWorkerFkOld, vYear, vWeek); - ELSE + ELSE ROLLBACK; END IF; @@ -74299,16 +74303,16 @@ proc: LOOP COMMIT; END LOOP; CLOSE vCursor; - + INSERT INTO mail (receiver, replyTo, subject, body) - SELECT CONCAT(u.name, '@verdnatura.es'), - CONCAT('Error registro de horas semana ', vWeek, ' año ', vYear) , + SELECT CONCAT(u.name, '@verdnatura.es'), + CONCAT('Error registro de horas semana ', vWeek, ' año ', vYear) , CONCAT('No se ha podido enviar el registro de horas al empleado/s: ', GROUP_CONCAT(DISTINCT CONCAT('
', w.id, ' ', w.firstName, ' ', w.lastName))) FROM tmp.error e JOIN worker w ON w.id = e.workerFk JOIN account.user u ON u.id = w.bossFk - GROUP BY w.bossFk; - + GROUP BY w.bossFk; + DROP TABLE tmp.timeControlCalculate; DROP TABLE tmp.timeBusinessCalculate; DROP TABLE tmp.timeControlCalculate1; @@ -74386,7 +74390,7 @@ BEGIN AND w.businessFk GROUP BY tm.userFk,t.dated ORDER BY tm.userFk,t.dated; - + INSERT INTO vn.mail (receiver, replyTo, subject, body) SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) , CONCAT(' @@ -74478,7 +74482,7 @@ BEGIN IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo; - + CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, NULL); END IF; END ;; @@ -74528,9 +74532,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas - * El sistema verificará el descanso corto en la siguiente semana - * o el largo en las 2 siguientes semanas a partir de las fechas dadas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * El sistema verificará el descanso corto en la siguiente semana + * o el largo en las 2 siguientes semanas a partir de las fechas dadas * @param vStarted día inicio para verificar * @param vEnded día final para verificar * @return tmp.workerWithoutWeekBreak (workerFk) @@ -74552,10 +74556,10 @@ BEGIN CALL workerTimeControl_checkBreak(vStarted); INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek - SELECT workerFk + SELECT workerFk FROM tmp.workerWithoutWeekBreak; DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak; - SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); + SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); END WHILE; END ;; @@ -74593,7 +74597,7 @@ BEGIN DECLARE vDepartmentFk INT; DECLARE isEnabled BOOLEAN DEFAULT TRUE; - SELECT COUNT(*) INTO vHasSignedToday + SELECT COUNT(*) INTO vHasSignedToday FROM workerTimeControl WHERE timed >= vDated AND userFk = vUserFk; SET @day := 0; @@ -74606,16 +74610,16 @@ BEGIN SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas FROM ( - SELECT @lastTimed fichada_anterior, + SELECT @lastTimed fichada_anterior, timed, CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes, IF(day(timed) != @day, 1, 0) as jornadas, @day := day(timed) dia_del_mes, - @lastTimed := timed fichada_actual + @lastTimed := timed fichada_actual FROM ( SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed - FROM + FROM (SELECT TIMESTAMPADD(DAY, -11, util.VN_NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior UNION ALL SELECT timed, userFk @@ -74623,18 +74627,18 @@ BEGIN WHERE userFk = vUserFk AND timed >= TIMESTAMPADD(DAY, -10,vDated) UNION ALL - SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk + SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk ) sub4 ORDER BY timed ) sub - + ) sub2 WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated) ) sub3 ; SELECT IFNULL(SUM(impar),0) into vImpares FROM ( - SELECT day(timed) as dayNumber, + SELECT day(timed) as dayNumber, count(*) mod 2 as impar FROM vn.workerTimeControl wtc WHERE userFk = vUserFk @@ -74651,29 +74655,29 @@ BEGIN AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + -- Contrato en vigor SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork FROM business b WHERE b.workerFk = vUserFk AND b.started <= vDated AND IFNULL(b.ended, vDated) >= vDated; - + -- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar) IF vTabletFk <> '0' THEN -- 1 Obtener el departamento del usuario SELECT wtcu.departmentFk INTO vDepartmentFk FROM workerTimeControlUserInfo wtcu WHERE wtcu.userFk = vUserFk; - -- 2 Comprobar si la tablet pertenece al departamento + -- 2 Comprobar si la tablet pertenece al departamento SELECT COUNT(td.tabletFk) INTO isEnabled FROM tabletDepartment td WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk; - + END IF; - + IF vJornadas IS NOT NULL THEN - + SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis UNION ALL SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis @@ -74682,9 +74686,9 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, - '' as Cantidad, - IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + '' as Cantidad, + IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -74698,7 +74702,7 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, '' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -74734,7 +74738,7 @@ CALL vn.workerTimeControlSetOrder_by_User_and_dateRange(vUserFk,TIMESTAMPADD(DAY DROP TEMPORARY TABLE IF EXISTS tmp.workerWeekTiming; CREATE TEMPORARY TABLE tmp.workerWeekTiming SELECT orden `orden`, - max(hace7dias) 7_dias_antes, + max(hace7dias) 7_dias_antes, max(hace6dias) 6_dias_antes, max(hace5dias) 5_dias_antes, max(hace4dias) 4_dias_antes, @@ -74764,16 +74768,16 @@ SELECT orden `orden`, )sub2 GROUP BY orden ; - + DROP TEMPORARY TABLE IF EXISTS tmp.workerWeekTiming_Aux; CREATE TEMPORARY TABLE tmp.workerWeekTiming_Aux SELECT * FROM tmp.workerWeekTiming; INSERT INTO tmp.workerWeekTiming( 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia) VALUES('total','','','','','','',''); - + INSERT INTO tmp.workerWeekTiming( orden, 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes, mismo_dia) -SELECT 0, +SELECT 0, IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(7_dias_antes), TIME_TO_SEC(7_dias_antes)))),'%H:%i'),''), IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(6_dias_antes), TIME_TO_SEC(6_dias_antes)))),'%H:%i'),''), IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(5_dias_antes), TIME_TO_SEC(5_dias_antes)))),'%H:%i'),''), @@ -74783,7 +74787,7 @@ SELECT 0, IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(1_dia_antes), TIME_TO_SEC(1_dia_antes)))),'%H:%i'),''), '' FROM tmp.workerWeekTiming_Aux; - + INSERT INTO tmp.workerWeekTiming_Aux( orden, 1_dia_antes) SELECT 0, ROUND(( IFNULL(TIME_TO_SEC(7_dias_antes),0) + @@ -74795,14 +74799,14 @@ SELECT 0, ROUND(( IFNULL(TIME_TO_SEC(1_dia_antes),0) ) / 3600,1) FROM tmp.workerWeekTiming - WHERE orden = 0; + WHERE orden = 0; INSERT INTO tmp.workerWeekTiming( 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia) SELECT '','','','','','',1_dia_antes,'' FROM tmp.workerWeekTiming_Aux WHERE orden = 0; - + SELECT 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia FROM tmp.workerWeekTiming; DROP TEMPORARY TABLE tmp.workerWeekTiming; @@ -74844,28 +74848,28 @@ BEGIN JOIN vn.worker wb ON ww.id = wb.bossFk GROUP BY wb.bossFk; */ - + SELECT plusTeamAmount, plusNewBornAmount, plusSalesAmount, minimumSalesByQuarter, plusTeamRange, plusNewBornRange, rankingSalesRange INTO vPlusTeamAmount, vPlusNewBornAmount, vPlusSalesAmount, vMinimumSalesByQuarter, vPlusTeamRange, vPlusNewBornRange, vRankingSalesRange FROM commissionConfig; -- Ventas DROP TEMPORARY TABLE IF EXISTS rankingSale; CREATE TEMPORARY TABLE rankingSale - (PRIMARY KEY(workerFk)) ENGINE = MEMORY - SELECT IF(SUM(v.importe) > vMinimumSalesByQuarter, + (PRIMARY KEY(workerFk)) ENGINE = MEMORY + SELECT IF(SUM(v.importe) > vMinimumSalesByQuarter, SUM(IFNULL(v.comision,0)), 0) as commission, SUM(v.importe) sales, v.Id_Trabajador workerFk - FROM bs.vendedores v + FROM bs.vendedores v WHERE v.año = vYear AND CEIL(mes/3) = vQuarter GROUP BY v.Id_Trabajador; - + -- Ranking ventas SET @position:= 0; DROP TEMPORARY TABLE IF EXISTS rankingSelling; CREATE TEMPORARY TABLE rankingSelling - (PRIMARY KEY(userFk)) ENGINE = MEMORY + (PRIMARY KEY(userFk)) ENGINE = MEMORY SELECT userFk, @position:= @position + 1 position FROM ( SELECT SUM(`v`.`importe`) AS `importe`, @@ -74882,29 +74886,29 @@ BEGIN ORDER BY SUM(`v`.`importe`) DESC LIMIT vRankingSalesRange ) t; - - CALL rankingTeamByQuarter(vYear, vQuarter); - + + CALL rankingTeamByQuarter(vYear, vQuarter); + -- comerciales que computan / total integrantes DROP TEMPORARY TABLE IF EXISTS teamNames; CREATE TEMPORARY TABLE teamNames - (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY SELECT DISTINCT departmentFk, teamPeople FROM tmp.rankingTeam; - - -- Ranking por equipos + + -- Ranking por equipos DROP TEMPORARY TABLE IF EXISTS rankingTeam; CREATE TEMPORARY TABLE rankingTeam - (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY SELECT DISTINCT departmentFk FROM teamNames LIMIT vPlusTeamRange; - + -- Ranking por nuevos clientes SET @position:= 0; DROP TEMPORARY TABLE IF EXISTS rankingNewBorn; CREATE TEMPORARY TABLE rankingNewBorn - (PRIMARY KEY(userFk)) ENGINE = MEMORY + (PRIMARY KEY(userFk)) ENGINE = MEMORY SELECT userFk, @position:= @position + 1 position FROM ( SELECT SUM(amount) AS total, @@ -74916,10 +74920,10 @@ BEGIN ORDER BY SUM(amount) DESC LIMIT vPlusNewBornRange ) t; - + -- Sumatorio de ventas - SELECT uBoss.`name` as team, - u.`name`, + SELECT uBoss.`name` as team, + u.`name`, r.commission, -- IF(rh.bossFk, 200 + (teamMembers * 30), 0) plusResponsibility, @plusRankingSellers := ((vRankingSalesRange + 1) - rs.position) * 40 plusRankingSellers, @@ -74937,11 +74941,11 @@ BEGIN LEFT JOIN rankingSelling rs ON rs.userFk = r.workerFk LEFT JOIN workerDepartment wd ON wd.workerFk = r.workerFk LEFT JOIN rankingTeam rt ON rt.departmentFk = wd.departmentFk AND r.commission - LEFT JOIN teamNames tn ON tn.departmentFk = wd.departmentFk + LEFT JOIN teamNames tn ON tn.departmentFk = wd.departmentFk LEFT JOIN vn.rankingNewBorn rnb ON rnb.userFk = r.workerFk; - + DROP TEMPORARY TABLE tmp.rankingTeam; - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE rankingSelling, rankingTeam, teamNames, @@ -74964,21 +74968,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getFromHasMistake`(vDepartmentFk INT) -BEGIN - -/** - * Obtiene los trabajadores de los departamentos que se les puede poner error - * @param vDepartmentFk id del departamento - * - */ - - SELECT w.id,w.firstName, w.lastName,d.name - FROM worker w - JOIN workerDepartment wd ON wd.workerFk = w.id - JOIN department d ON d.id = wd.departmentFk - WHERE d.id = vDepartmentFk - ORDER BY firstName; - +BEGIN + +/** + * Obtiene los trabajadores de los departamentos que se les puede poner error + * @param vDepartmentFk id del departamento + * + */ + + SELECT w.id,w.firstName, w.lastName,d.name + FROM worker w + JOIN workerDepartment wd ON wd.workerFk = w.id + JOIN department d ON d.id = wd.departmentFk + WHERE d.id = vDepartmentFk + ORDER BY firstName; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75006,7 +75010,7 @@ BEGIN (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBoss AS workerFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchyList; CREATE TEMPORARY TABLE tmp.workerHierarchyList (PRIMARY KEY (workerFk)) @@ -75017,7 +75021,7 @@ BEGIN WHILE (SELECT COUNT(*) FROM tmp.workerHierarchyList WHERE NOT isChecked) > 0 DO INSERT INTO tmp.workerHierarchyList - SELECT w.id, 0 + SELECT w.id, 0 FROM worker w JOIN workerHierarchy wh ON wh.workerFk = w.bossFk; @@ -75028,12 +75032,12 @@ BEGIN TRUNCATE workerHierarchy; INSERT INTO workerHierarchy - SELECT workerFk + SELECT workerFk FROM tmp.workerHierarchyList WHERE NOT isChecked; END WHILE; - + DROP TEMPORARY TABLE IF EXISTS workerHierarchy; END ;; DELIMITER ; @@ -75052,17 +75056,17 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getSector`() -BEGIN - -/** - * Obtiene el sector del usuario conectado -*/ - - SELECT s.id,s.description,s.warehouseFk - FROM sector s - JOIN worker w ON w.sectorFk = s.id - WHERE w.id = account.myUser_getId(); - +BEGIN + +/** + * Obtiene el sector del usuario conectado +*/ + + SELECT s.id,s.description,s.warehouseFk + FROM sector s + JOIN worker w ON w.sectorFk = s.id + WHERE w.id = account.myUser_getId(); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75145,8 +75149,8 @@ BEGIN DECLARE vDone BOOL; DECLARE vCursor CURSOR FOR - SELECT DISTINCT b.workerFk - FROM business b + SELECT DISTINCT b.workerFk + FROM business b WHERE b.started > vBusinessUpdated AND b.started <= vCurdate OR b.ended >= vBusinessUpdated AND b.ended < vCurdate; @@ -75187,18 +75191,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateSector`(vSectorFk INT) -BEGIN - -/** - * Actualiza el sector del usuario conectado y borra la impresora asociada al usuario - * - * @param vSectorFk id del sector -*/ - UPDATE worker - SET sectorFk = vSectorFk, - labelerFk = NULL - WHERE id = account.myUser_getId(); - +BEGIN + +/** + * Actualiza el sector del usuario conectado y borra la impresora asociada al usuario + * + * @param vSectorFk id del sector +*/ + UPDATE worker + SET sectorFk = vSectorFk, + labelerFk = NULL + WHERE id = account.myUser_getId(); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75218,10 +75222,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHours`(username varchar(255), logon boolean) BEGIN DECLARE userid int(11); - + SELECT vn.getUserId(username) INTO userid; SELECT username, userid; - IF userid IS NOT NULL THEN + IF userid IS NOT NULL THEN IF (logon) THEN CALL vn.workingHoursTimeIn(userid); ELSE @@ -75290,17 +75294,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `wrongEqualizatedClient`() BEGIN SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num FROM vn.client c - JOIN + JOIN ( - SELECT DISTINCT + SELECT DISTINCT `a`.`clientFk` , a.isEqualizated = 0 as ie - + FROM `vn`.`address` `a` ) sub ON sub.clientFk = c.id WHERE c.hasToInvoiceByAddress = FALSE - + GROUP BY clientFk HAVING num > 1 UNION ALL @@ -75384,27 +75388,27 @@ proc: BEGIN SELECT scope INTO vScope FROM zoneConfig; - + DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone (INDEX (id)) ENGINE = MEMORY SELECT id FROM zone; - + TRUNCATE TABLE zoneClosure; - + WHILE vCounter <= vScope DO - + CALL zone_getOptionsForShipment(vShipped, TRUE); - + REPLACE zoneClosure(zoneFk, dated, `hour`) - SELECT zoneFk, vShipped, `hour` + SELECT zoneFk, vShipped, `hour` FROM tmp.zoneOption; - + SET vCounter = vCounter + 1; SET vShipped = TIMESTAMPADD(DAY, 1, vShipped); END WHILE; - + -- DROP TEMPORARY TABLE tmp.zone; DO RELEASE_LOCK('vn.zoneClosure_recalc'); END ;; @@ -75498,7 +75502,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -75509,11 +75513,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL zoneGeo_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -75616,7 +75620,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM zoneGeoRecalc; - + IF vIsChanged THEN UPDATE zoneGeoRecalc SET isChanged = FALSE; CALL vn.zoneGeo_calcTree; @@ -75804,7 +75808,7 @@ proc:BEGIN * @table tmp.closedZones(zoneFk, warehouseFk); */ DROP TEMPORARY TABLE IF EXISTS tmp.closedZones; - + CREATE TEMPORARY TABLE tmp.closedZones ( `zoneFk` int(11) NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, @@ -75846,7 +75850,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getCollisions`() BEGIN /** - * Calcula si para un mismo codigo postal y dia + * Calcula si para un mismo codigo postal y dia * hay mas de una zona configurada y manda correo * */ @@ -75855,16 +75859,16 @@ BEGIN DECLARE vIsDone INT DEFAULT FALSE; DECLARE vTableCollisions TEXT; DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone - SELECT z.id + SELECT z.id FROM zone z JOIN agencyMode am ON am.id = z.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN ('AGENCY','DELIVERY'); + WHERE dm.code IN ('AGENCY','DELIVERY'); CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE); @@ -75879,7 +75883,7 @@ BEGIN PRIMARY KEY zoneFkk (zoneFk, geoFk), INDEX(geoFk)) ENGINE = MEMORY; - + OPEN cur1; cur1Loop: LOOP SET vIsDone = FALSE; @@ -75887,40 +75891,40 @@ BEGIN IF vIsDone THEN LEAVE cur1Loop; END IF; - + CALL zone_getLeaves2(vZoneFk, NULL, NULL); - myLoop: LOOP + myLoop: LOOP SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk + SELECT geoFk INTO vGeoFk FROM tmp.zoneNodes zn WHERE NOT isChecked LIMIT 1; - + IF vGeoFk IS NULL THEN LEAVE myLoop; END IF; - + CALL zone_getLeaves2(vZoneFk, vGeoFk, NULL); UPDATE tmp.zoneNodes - SET isChecked = TRUE + SET isChecked = TRUE WHERE geoFk = vGeoFk; END LOOP; END LOOP; CLOSE cur1; - DELETE FROM tmp.zoneNodes + DELETE FROM tmp.zoneNodes WHERE sons > 0; - + DROP TEMPORARY TABLE IF EXISTS geoCollision; CREATE TEMPORARY TABLE geoCollision SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk - JOIN zoneWarehouse zw ON z.id = zw.zoneFk + JOIN zoneWarehouse zw ON z.id = zw.zoneFk GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk HAVING count(*) > 1; - + SELECT '
Según la información recogida en el sistema adjuntamos la tabla con los registros de las horas trabajadas en el período indicado. Si está conforme tiene que contestar indicando únicamente la palabra OK, en caso contrario puede contestar detallando la causa de la disconformidad. - Rogamos nos conteste lo antes posible. + Rogamos nos conteste lo antes posible.

@@ -75930,39 +75934,39 @@ BEGIN ' INTO vTableCollisions; - - INSERT INTO mail (receiver,replyTo,subject,body) + + INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'pepe@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject, CONCAT(vTableCollisions, GROUP_CONCAT(sub.td SEPARATOR ''), '
C.PostalAlmacén Salix
') body - FROM(SELECT + FROM(SELECT CONCAT(' ', zn.name, ' ', zoneFk,' ', z.price,' ', z.name,' ', w.name, ' - ', CONCAT('' - 'https://salix.verdnatura.es/#!/zone/', + 'https://salix.verdnatura.es/#!/zone/', zoneFk, '/location?q=%7B%22search%22:%22', - zn.name, + zn.name, '%22%7D'),' ') td FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk JOIN warehouse w ON w.id = gc.warehouseFk) sub; - - DROP TEMPORARY TABLE - geoCollision, + + DROP TEMPORARY TABLE + geoCollision, tmp.zone, tmp.zoneNodes; END ;; @@ -75992,17 +75996,17 @@ BEGIN * @param vAgencyModeFk The agency mode id */ DECLARE vDeliveryMethodFk VARCHAR(255); - + DROP TEMPORARY TABLE IF EXISTS tZone; CREATE TEMPORARY TABLE tZone (id INT PRIMARY KEY) ENGINE = MEMORY; - + SELECT dm.`code` INTO vDeliveryMethodFk FROM agencyMode am JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk WHERE am.id = vAgencyModeFk; - + IF vDeliveryMethodFk = 'PICKUP' THEN INSERT INTO tZone SELECT id @@ -76019,16 +76023,16 @@ BEGIN WHERE z.agencyModeFk = vAgencyModeFk; ELSE INSERT INTO tZone - SELECT t.id + SELECT t.id FROM tmp.zone t JOIN zone z ON z.id = t.id - JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN agencyMode am ON am.id = z.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk WHERE dm.`code` IN ('AGENCY', 'DELIVERY'); END IF; DROP TEMPORARY TABLE tmp.zone; END IF; - + SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays FROM tZone t JOIN zoneEvent e ON e.zoneFk = t.id; @@ -76040,7 +76044,7 @@ BEGIN JOIN zoneGeo zg1 ON zg1.id = eg.geoFk JOIN zoneGeo zg2 ON zg2.id = vGeoFk WHERE eg.zoneExclusionFk IS NULL OR zg2.`path` LIKE CONCAT(zg1.`path`,'%'); - + DROP TEMPORARY TABLE tZone; END ;; DELIMITER ; @@ -76069,18 +76073,18 @@ BEGIN 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; @@ -76088,7 +76092,7 @@ BEGIN SELECT vChildFk, vLevel FROM DUAL WHERE vChildFk IS NOT NULL; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; @@ -76188,7 +76192,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`(vSelf INT, vParentFk INT, vSearch VARCHAR(255)) -BEGIN +BEGIN /** * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. * @param vSelf Id de la zona @@ -76202,23 +76206,23 @@ BEGIN CREATE TEMPORARY TABLE tNodes (UNIQUE (id)) ENGINE = MEMORY - SELECT id - FROM zoneGeo + SELECT id + FROM zoneGeo LIMIT 0; IF vIsSearch THEN SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - + INSERT INTO tNodes - SELECT id + 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 + SELECT geoFk FROM zoneIncluded WHERE zoneFk = vSelf; END IF; @@ -76227,14 +76231,14 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tChilds; CREATE TEMPORARY TABLE tChilds ENGINE = MEMORY - SELECT id + SELECT id FROM tNodes; DROP TEMPORARY TABLE IF EXISTS tParents; CREATE TEMPORARY TABLE tParents ENGINE = MEMORY - SELECT id - FROM zoneGeo + SELECT id + FROM zoneGeo LIMIT 0; myLoop: LOOP @@ -76244,27 +76248,27 @@ BEGIN FROM zoneGeo g JOIN tChilds c ON c.id = g.id WHERE g.parentFk IS NOT NULL; - + INSERT IGNORE INTO tNodes - SELECT id + SELECT id FROM tParents; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; - + DELETE FROM tChilds; INSERT INTO tChilds - SELECT id + SELECT id FROM tParents; END LOOP; - + DROP TEMPORARY TABLE tChilds, tParents; END IF; IF !vIsSearch THEN INSERT IGNORE INTO tNodes - SELECT id + SELECT id FROM zoneGeo WHERE parentFk <=> vParentFk; END IF; @@ -76297,106 +76301,106 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves2`(vSelf INT, vParentFk INT, vSearch VARCHAR(255)) -BEGIN -/** - * Devuelve los geoFk incluidos en la ruta y que sean hijos de parentFk - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch cadena a buscar - * - * @return tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - * - */ - 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 - (INDEX(id)) - ENGINE = MEMORY - SELECT id - FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id - FROM tParents; - - IF 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; - - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT g.id, - g.`name`, - g.parentFk, - g.sons, - NOT g.sons OR type = 'country', - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id AND i.zoneFk = vSelf - WHERE i.isIncluded = TRUE - OR (i.isIncluded IS NULL AND vParentFk IS NOT NULL); - - DROP TEMPORARY TABLE tNodes; +BEGIN +/** + * Devuelve los geoFk incluidos en la ruta y que sean hijos de parentFk + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch cadena a buscar + * + * @return tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + * + */ + 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 + (INDEX(id)) + ENGINE = MEMORY + SELECT id + FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id + FROM tParents; + + IF 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; + + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + NOT g.sons OR type = 'country', + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id AND i.zoneFk = vSelf + WHERE i.isIncluded = TRUE + OR (i.isIncluded IS NULL AND vParentFk IS NOT NULL); + + DROP TEMPORARY TABLE tNodes; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76421,7 +76425,7 @@ BEGIN * @table tmp.zone(id) The zones ids * @param vLanded The delivery date * @return tmp.zoneOption The computed options - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY @@ -76462,13 +76466,13 @@ BEGIN END LIMIT 10000000000000000000 ) t - GROUP BY zoneFk; - + GROUP BY zoneFk; + DELETE t FROM tmp.zoneOption t JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + IF NOT vShowExpiredZones THEN DELETE FROM tmp.zoneOption WHERE shipped < util.VN_CURDATE() @@ -76500,7 +76504,7 @@ BEGIN * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options */ DECLARE vHour TIME DEFAULT TIME(util.VN_NOW()); - + DROP TEMPORARY TABLE IF EXISTS tLandings; CREATE TEMPORARY TABLE tLandings (INDEX (eventFk)) @@ -76582,7 +76586,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) BEGIN /** * Devuelve los códigos postales incluidos en una zona - */ + */ DECLARE vGeoFk INT DEFAULT NULL; DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; @@ -76603,16 +76607,16 @@ BEGIN SET isChecked = 0 WHERE parentFk IS NULL; - myLoop: LOOP + myLoop: LOOP SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk + SELECT geoFk INTO vGeoFk FROM tmp.zoneNodes zn WHERE NOT isChecked LIMIT 1; CALL zone_getLeaves2(vSelf, vGeoFk, NULL); UPDATE tmp.zoneNodes - SET isChecked = TRUE + SET isChecked = TRUE WHERE geoFk = vGeoFk; IF vGeoFk IS NULL THEN @@ -76620,7 +76624,7 @@ BEGIN END IF; END LOOP; - DELETE FROM tmp.zoneNodes + DELETE FROM tmp.zoneNodes WHERE sons > 0; SELECT zn.geoFk, zn.name @@ -76656,7 +76660,7 @@ BEGIN DECLARE vZoneGeo INT; SELECT address_getGeo(vAddressFk) INTO vZoneGeo; - + CALL vn.zone_getFromGeo(vZoneGeo); CALL vn.zone_getOptionsForLanding(vLanded, vShowExpiredZones); CALL vn.zone_excludeFromGeo(vZoneGeo); @@ -76676,7 +76680,7 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zoneWarehouse zw ON zw.zoneFk = zo.zoneFk JOIN vn.`zone` z ON z.id = zo.zoneFk - LEFT JOIN tmp.closedZones cz + LEFT JOIN tmp.closedZones cz ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zw.zoneFk AND zo.shipped = util.VN_CURDATE() @@ -76710,9 +76714,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getState`(vDated DATE) BEGIN /** * Devuelve las zonas y el estado para la fecha solicitada - * + * * @param vDated Fecha en cuestión - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone ( @@ -76726,7 +76730,7 @@ BEGIN CALL vn.zone_getOptionsForShipment(vDated, TRUE); CALL vn.zone_getClosed(); - + SELECT zo.zoneFk, zo.`hour`etd, (zo.`hour` <= TIME(util.VN_NOW())) isLate, @@ -76736,11 +76740,11 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zone z ON z.id = zo.zoneFk JOIN vn.zoneWarehouse zw ON zw.zoneFk = z.id - LEFT JOIN tmp.closedZones cz - ON cz.warehouseFk = zw.warehouseFk + LEFT JOIN tmp.closedZones cz + ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zo.zoneFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.closedZones, tmp.zoneOption, tmp.zone; @@ -76766,21 +76770,21 @@ 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, FALSE); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, zw.warehouseFk, z.id zoneFk FROM tmp.zoneOption zo @@ -76790,11 +76794,11 @@ BEGIN WHERE zw.warehouseFk = vWarehouse GROUP BY z.agencyModeFk ORDER BY agencyMode; - + DROP TEMPORARY TABLE tmp.zone, tmp.zoneOption; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76815,7 +76819,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_upcomingDeliveries`() BEGIN DECLARE vForwardDays INT; - + SELECT forwardDays INTO vForwardDays FROM zoneConfig; CALL util.time_createTable(util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL vForwardDays DAY)); @@ -76831,7 +76835,7 @@ BEGIN JOIN zoneEvent e ON e.zoneFk = z.id JOIN tmp.time ti ON ti.dated BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vForwardDays, util.VN_CURDATE()); - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY SELECT * @@ -76872,7 +76876,7 @@ BEGIN JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + SELECT MAX(zo.`hour`) `hour`, zg.`name`, zo.shipped, zo.zoneFk FROM tmp.zoneOption zo JOIN `zone` z ON z.id = zo.zoneFk @@ -76883,10 +76887,13 @@ BEGIN WHERE dm.code = 'DELIVERY' GROUP BY shipped, zg.`name` ORDER BY shipped, zg.`name`; - + DROP TEMPORARY TABLE tmp.time, 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 */ ; @@ -76981,6 +76988,17 @@ DELIMITER ; -- -- Current Database: `account` -- +-- Fix strucuture +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('ZipConfig', '*', '*', 'ALLOW', 'ROLE', 'employee'); + +DROP TABLE IF EXISTS `vn`.`zipConfig`; +CREATE TABLE `vn`.`zipConfig` ( + `id` double(10,2) NOT NULL, + `maxSize` int(11) DEFAULT NULL COMMENT 'in MegaBytes', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; USE `account`; @@ -77556,6 +77574,7 @@ USE `hedera`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `orderTicket` -- diff --git a/modules/worker/back/methods/worker-time-control/sendMail.js b/modules/worker/back/methods/worker-time-control/sendMail.js index 2f9559b3a..cd9cacbd7 100644 --- a/modules/worker/back/methods/worker-time-control/sendMail.js +++ b/modules/worker/back/methods/worker-time-control/sendMail.js @@ -133,7 +133,7 @@ module.exports = Self => { tb.permissionRate, d.isTeleworking FROM tmp.timeBusinessCalculate tb - JOIN user u ON u.id = tb.userFk + JOIN account.user u ON u.id = tb.userFk JOIN department d ON d.id = tb.departmentFk JOIN business b ON b.id = tb.businessFk LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated @@ -143,7 +143,7 @@ module.exports = Self => { IF(tc.timeWorkDecimal > 0, FALSE, IF(tb.timeWorkDecimal > 0, TRUE, FALSE)), TRUE))isTeleworkingWeek FROM tmp.timeBusinessCalculate tb - LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated GROUP BY tb.userFk HAVING isTeleworkingWeek > 0