diff --git a/.vscode/settings.json b/.vscode/settings.json index deb4b49e1..2298e4846 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,8 @@ // Carácter predeterminado de final de línea. "files.eol": "\n", "vsicons.presets.angular": false, - "eslint.autoFixOnSave": true + "eslint.autoFixOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } } \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index 0aaba1e93..0d56f7476 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -8,19 +8,17 @@ pipeline { environment { PROJECT_NAME = 'salix' REGISTRY = 'registry.verdnatura.es' - DOCKER_HOST_1 = 'vch1.verdnatura.es' - DOCKER_HOST_2 = 'vch2.verdnatura.es' PORT_MASTER_FRONT = '5002' - PORT_MASTER_BACK = '3001-3002' + PORT_MASTER_BACK = '3001' PORT_TEST_FRONT = '5001' - PORT_TEST_BACK = '4001-4002' + PORT_TEST_BACK = '4001' TAG = "${env.BRANCH_NAME}" } stages { stage('Checkout') { steps { script { - env.COMPOSE_PROJECT_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" + env.STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" if (!env.GIT_COMMITTER_EMAIL) { env.COMMITTER_EMAIL = sh( @@ -65,18 +63,23 @@ pipeline { } } stage('Test') { - when { not { anyOf { - branch 'test' - branch 'master' - }}} environment { NODE_ENV = "" - FIREFOX_BIN = "/opt/firefox/firefox-bin" } - steps { - nodejs('node-lts') { - sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' - sh 'gulp backTestDockerOnce --junit --random' + parallel { + stage('Frontend') { + steps { + nodejs('node-lts') { + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' + } + } + } + stage('Backend') { + steps { + nodejs('node-lts') { + sh 'gulp backTestDockerOnce --junit --random' + } + } } } } @@ -103,32 +106,8 @@ pipeline { branch 'test' branch 'master' }} - environment { - DOCKER_TLS_VERIFY = 1 - } - parallel { - stage('Host 1') { - environment { - DOCKER_HOST = "tcp://${env.DOCKER_HOST_1}:2376" - } - steps { - withCredentials([dockerCert(credentialsId: 'docker', variable: 'DOCKER_CERT_PATH')]) { - sh 'docker-compose pull' - sh 'docker-compose up -d --scale back=2' - } - } - } - stage('Host 2') { - environment { - DOCKER_HOST = "tcp://${env.DOCKER_HOST_2}:2376" - } - steps { - withCredentials([dockerCert(credentialsId: 'docker', variable: 'DOCKER_CERT_PATH')]) { - sh 'docker-compose pull' - sh 'docker-compose up -d --scale back=2' - } - } - } + steps { + sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}" } } stage('Database') { @@ -147,15 +126,6 @@ pipeline { sh 'db/import-changes.sh -f $NODE_ENV' } } - stage('Cleanup') { - when { anyOf { - branch 'test' - branch 'master' - }} - steps { - sh 'docker logout $REGISTRY' - } - } } post { always { diff --git a/back/methods/chat/sendMessage.js b/back/methods/chat/sendMessage.js index 2ab07af8c..a861ba07e 100644 --- a/back/methods/chat/sendMessage.js +++ b/back/methods/chat/sendMessage.js @@ -31,26 +31,23 @@ module.exports = Self => { const recipient = to.replace('@', ''); if (sender.name != recipient) - return sendMessage(to, `@${sender.name}: ${message}`); + return sendMessage(sender, to, `@${sender.name}: ${message} `); }; - async function sendMessage(name, message) { - const models = Self.app.models; - const chatConfig = await models.ChatConfig.findOne(); + async function sendMessage(sender, channel, message) { + const config = await getConfig(); - if (!Self.token) - Self.token = await login(); - - const uri = `${chatConfig.uri}/chat.postMessage`; - return send(uri, { - 'channel': name, + const avatar = `${config.host}/avatar/${sender.name}`; + const uri = `${config.api}/chat.postMessage`; + return sendAuth(uri, { + 'channel': channel, + 'avatar': avatar, 'text': message }).catch(async error => { - if (error.statusCode === 401 && !Self.loginAttempted) { - Self.token = await login(); - Self.loginAttempted = true; + if (error.statusCode === 401 && !this.resendAttempted) { + this.resendAttempted = true; - return sendMessage(name, message); + return sendMessage(sender, channel, message); } throw new Error(error.message); @@ -61,24 +58,51 @@ module.exports = Self => { * Returns a rocketchat token * @return {Object} userId and authToken */ - async function login() { - const models = Self.app.models; - const chatConfig = await models.ChatConfig.findOne(); - const uri = `${chatConfig.uri}/login`; - return send(uri, { - user: chatConfig.user, - password: chatConfig.password - }).then(res => res.data); + async function getAuthToken() { + if (!this.auth || this.auth && !this.auth.authToken) { + const config = await getConfig(); + const uri = `${config.api}/login`; + const res = await send(uri, { + user: config.user, + password: config.password + }); + + this.auth = res.data; + } + + return this.auth; } - function send(uri, body) { + /** + * Returns a rocketchat config + * @return {Object} Auth config + */ + async function getConfig() { + if (!this.chatConfig) { + const models = Self.app.models; + + this.chatConfig = await models.ChatConfig.findOne(); + } + + return this.chatConfig; + } + + /** + * Send unauthenticated request + * @param {*} uri - Request uri + * @param {*} body - Request params + * @param {*} options - Request options + * + * @return {Object} Request response + */ + async function send(uri, body, options) { if (process.env.NODE_ENV !== 'production') { return new Promise(resolve => { return resolve({statusCode: 200, message: 'Fake notification sent'}); }); } - const options = { + const defaultOptions = { method: 'POST', uri: uri, body: body, @@ -86,11 +110,29 @@ module.exports = Self => { json: true }; - if (Self.token) { - options.headers['X-Auth-Token'] = Self.token.authToken; - options.headers['X-User-Id'] = Self.token.userId; + if (options) Object.assign(defaultOptions, options); + + return request(defaultOptions); + } + + /** + * Send authenticated request + * @param {*} uri - Request uri + * @param {*} body - Request params + * + * @return {Object} Request response + */ + async function sendAuth(uri, body) { + const login = await getAuthToken(); + const options = { + headers: {'content-type': 'application/json'} + }; + + if (login) { + options.headers['X-Auth-Token'] = login.authToken; + options.headers['X-User-Id'] = login.userId; } - return request(options); + return send(uri, body, options); } }; diff --git a/back/models/chat-config.json b/back/models/chat-config.json index 12cd021cb..d4f708b7a 100644 --- a/back/models/chat-config.json +++ b/back/models/chat-config.json @@ -13,7 +13,10 @@ "type": "Number", "description": "Identifier" }, - "uri": { + "host": { + "type": "String" + }, + "api": { "type": "String" }, "user": { diff --git a/back/models/user-phone-type.json b/back/models/user-phone-type.json index 479f02d6f..9410bd8db 100644 --- a/back/models/user-phone-type.json +++ b/back/models/user-phone-type.json @@ -14,5 +14,13 @@ "description": { "type": "String" } - } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] } diff --git a/db/changes/10080-september/00-catalog_calculate.sql b/db/changes/10080-september/00-catalog_calculate.sql deleted file mode 100644 index 4ddb79274..000000000 --- a/db/changes/10080-september/00-catalog_calculate.sql +++ /dev/null @@ -1,117 +0,0 @@ -DROP procedure IF EXISTS `vn`.`catalog_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_calculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/00-address_getGeo.sql b/db/changes/10081-agency/00-address_getGeo.sql deleted file mode 100644 index fca55dfd2..000000000 --- a/db/changes/10081-agency/00-address_getGeo.sql +++ /dev/null @@ -1,27 +0,0 @@ - -DROP FUNCTION IF EXISTS `vn`.`address_getGeo`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`address_getGeo` (vSelf INT) - RETURNS INT - DETERMINISTIC -BEGIN -/** - * Returns the geo for the passed address. - * - * @param vSelf The address id - * @return The geo id - */ - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode - WHERE a.id = vSelf - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - RETURN vGeoFk; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone.sql b/db/changes/10081-agency/00-zone.sql deleted file mode 100644 index 74e482c4c..000000000 --- a/db/changes/10081-agency/00-zone.sql +++ /dev/null @@ -1,56 +0,0 @@ -USE `vn`; - -CREATE TABLE `vn`.`zoneWarehouse` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), - KEY `warehouseFk` (`warehouseFk`), - CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE/*, -CONSTRAINT `zoneWarehouse_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE*/ -) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; - -CREATE TABLE `vn`.`zoneEvent` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `from` date DEFAULT NULL, - `to` date DEFAULT NULL, - `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, - `hour` datetime DEFAULT NULL, - `travelingDays` int(11) DEFAULT NULL, - `price` decimal(10,2) DEFAULT NULL, - `bonus` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `zoneFk` (`zoneFk`), - CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8; - -ALTER TABLE `vn`.`zoneEvent` - ADD COLUMN `type` ENUM('day', 'indefinitely', 'range') NOT NULL AFTER `zoneFk`, - ADD COLUMN `dated` DATE NULL DEFAULT NULL AFTER `type`, - CHANGE COLUMN `from` `started` DATE NULL DEFAULT NULL , - CHANGE COLUMN `to` `ended` DATE NULL DEFAULT NULL ; - -CREATE TABLE `vn`.`zoneExclusion` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `day` date NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `zoneFk_2` (`zoneFk`,`day`), - KEY `zoneFk` (`zoneFk`), - CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -ALTER TABLE `vn`.`zone` -DROP FOREIGN KEY `fk_zone_1`; -ALTER TABLE `vn`.`zone` -CHANGE COLUMN `warehouseFk` `warehouseFk` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ; -ALTER TABLE `vn`.`zone` -ADD CONSTRAINT `fk_zone_1` - FOREIGN KEY (`warehouseFk`) - REFERENCES `vn`.`warehouse` (`id`) - ON DELETE NO ACTION - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`zoneExclusion` - CHANGE COLUMN `day` `dated` DATE NOT NULL ; diff --git a/db/changes/10081-agency/00-zone_getAvailable.sql b/db/changes/10081-agency/00-zone_getAvailable.sql deleted file mode 100644 index d24816e6e..000000000 --- a/db/changes/10081-agency/00-zone_getAvailable.sql +++ /dev/null @@ -1,16 +0,0 @@ - -DROP PROCEDURE IF EXISTS `vn`.`zone_getAvailable`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getAvailable`(vAddress INT, vLanded DATE) -BEGIN - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - SELECT * FROM tmp.zoneOption; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getEvents.sql b/db/changes/10081-agency/00-zone_getEvents.sql deleted file mode 100644 index be50f602d..000000000 --- a/db/changes/10081-agency/00-zone_getEvents.sql +++ /dev/null @@ -1,52 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getEvents`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( - vProvinceFk INT, - vPostCode VARCHAR(255), - vAgencyModeFk INT) -BEGIN -/** - * Returns available events for the passed province/postcode and agency. - * - * @param vAgencyModeFk The agency mode id - * @param vProvinceFk The province id - * @param vPostCode The postcode or %NULL to use the province - */ - DECLARE vGeoFk INT; - - IF vPostCode IS NOT NULL THEN - SELECT p.geoFk INTO vGeoFk - FROM postCode p - JOIN town t ON t.id = p.townFk - WHERE p.`code` = vPostCode - AND t.provinceFk = vProvinceFk; - ELSE - SELECT geoFk INTO vGeoFk - FROM province - WHERE id = vProvinceFk; - END IF; - - CALL zone_getFromGeo(vGeoFk); - - IF vAgencyModeFk IS NOT NULL THEN - DELETE t FROM tmp.zone t - JOIN zone z ON z.id = t.id - WHERE z.agencyModeFk != vAgencyModeFk; - END IF; - - SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays - FROM tmp.zone t - JOIN zoneEvent e ON e.zoneFk = t.id; - - SELECT e.zoneFk, e.dated - FROM tmp.zone t - JOIN zoneExclusion e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE tmp.zone; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getFromGeo.sql b/db/changes/10081-agency/00-zone_getFromGeo.sql deleted file mode 100644 index 244c73556..000000000 --- a/db/changes/10081-agency/00-zone_getFromGeo.sql +++ /dev/null @@ -1,58 +0,0 @@ - -DROP PROCEDURE IF EXISTS `vn`.`zone_getFromGeo`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getFromGeo`(vGeoFk INT) -BEGIN -/** - * Returns all zones which have the passed geo included. - * - * @param vGeoFk The geo id - * @return tmp.zone(id) The list of zones - */ - DECLARE vChildFk INT DEFAULT vGeoFk; - DECLARE vParentFk INT; - DECLARE vLevel INT DEFAULT 1; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT vGeoFk id, vLevel `level`; - - myLoop: LOOP - SELECT parentFk INTO vParentFk - FROM zoneGeo - WHERE id = vChildFk; - - SET vChildFk = vParentFk; - SET vLevel = vLevel + 1; - - INSERT IGNORE INTO tNodes - SELECT vChildFk, vLevel - FROM DUAL - WHERE vChildFk IS NOT NULL; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - END LOOP; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE tmp.zone - (INDEX (id)) - ENGINE = MEMORY - SELECT id FROM ( - SELECT zoneFk id, isIncluded - FROM ( - SELECT i.zoneFk, i.isIncluded - FROM tNodes n - JOIN zoneIncluded i ON i.geoFk = n.id - ORDER BY zoneFk, n.`level` - ) t - GROUP BY id HAVING isIncluded - ) t; - - DROP TEMPORARY TABLE tNodes; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getLeaves.sql b/db/changes/10081-agency/00-zone_getLeaves.sql deleted file mode 100755 index ee95b3315..000000000 --- a/db/changes/10081-agency/00-zone_getLeaves.sql +++ /dev/null @@ -1,88 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`zone_getLeaves`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255) -) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE - tChilds, - tParents; - END IF; - - IF !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - SELECT g.id, - g.`name`, - g.parentFk, - g.sons, - isIncluded selected - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i - ON i.geoFk = g.id AND i.zoneFk = vSelf - ORDER BY depth, selected DESC, `name`; - - DROP TEMPORARY TABLE tNodes; -END$$ -DELIMITER ; diff --git a/db/changes/10081-agency/01-zone_getAgency.sql b/db/changes/10081-agency/01-zone_getAgency.sql deleted file mode 100644 index 3d0c86866..000000000 --- a/db/changes/10081-agency/01-zone_getAgency.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT am.name agencyMode, - am.description, - z.agencyModeFk, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - TRUE isIncluded, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - GROUP BY agencyModeFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getFirstShipped.sql b/db/changes/10081-agency/01-zone_getFirstShipped.sql deleted file mode 100644 index 64e853a81..000000000 --- a/db/changes/10081-agency/01-zone_getFirstShipped.sql +++ /dev/null @@ -1,2 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getFirstShipped`; diff --git a/db/changes/10081-agency/01-zone_getLanded.sql b/db/changes/10081-agency/01-zone_getLanded.sql deleted file mode 100644 index a2bbe46a5..000000000 --- a/db/changes/10081-agency/01-zone_getLanded.sql +++ /dev/null @@ -1,40 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getLanded`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia -* @param vWarehouseFk vWarehouseFk -* @table tmp.zoneGetLanded Datos de recepción -*/ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT vWarehouseFk warehouseFk, - TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN zoneWarehouse zw ON zw.zoneFk = z.id - WHERE agencyModeFk = vAgencyModeFk - AND zw.warehouseFk = vWarehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql b/db/changes/10081-agency/01-zone_getShippedWarehouse.sql deleted file mode 100644 index 017b7d17c..000000000 --- a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql +++ /dev/null @@ -1,41 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vLanded); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT zo.zoneFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.agencyModeFk - FROM tmp.zoneOption zo - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - JOIN zone z ON z.id = zo.zoneFk - WHERE z.agencyModeFk = vAgencyModeFk - ORDER BY shipped) t - GROUP BY warehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getWarehouse.sql b/db/changes/10081-agency/01-zone_getWarehouse.sql deleted file mode 100644 index 28478e2cc..000000000 --- a/db/changes/10081-agency/01-zone_getWarehouse.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha, - * dirección y almacén pasados. - * - * @param vAddress - * @param vWarehouse warehouse - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.id zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - WHERE zw.warehouseFk - GROUP BY z.agencyModeFk - ORDER BY agencyMode; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetAgency.sql b/db/changes/10081-agency/02-zoneGetAgency.sql deleted file mode 100644 index 3a627ba5b..000000000 --- a/db/changes/10081-agency/02-zoneGetAgency.sql +++ /dev/null @@ -1,22 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`zoneGetAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vDate Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getAgency(vAddress,vLanded); -END$$ - -DELIMITER ; -; diff --git a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql b/db/changes/10081-agency/02-zoneGetFirstShipped__.sql deleted file mode 100644 index 9483f309c..000000000 --- a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql +++ /dev/null @@ -1,3 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`zoneGetFirstShipped`; diff --git a/db/changes/10081-agency/02-zoneGetLanded.sql b/db/changes/10081-agency/02-zoneGetLanded.sql deleted file mode 100644 index da8d8a9dd..000000000 --- a/db/changes/10081-agency/02-zoneGetLanded.sql +++ /dev/null @@ -1,20 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetLanded`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) -BEGIN -/** -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddress Id de consignatario, %NULL para recogida -* @param vAgencyMode Id agencia -* @table tmp.zoneGetLanded Datos de recepción -*/ - CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetShipped.sql b/db/changes/10081-agency/02-zoneGetShipped.sql deleted file mode 100644 index 212eb94df..000000000 --- a/db/changes/10081-agency/02-zoneGetShipped.sql +++ /dev/null @@ -1,24 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetShipped`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** - * OBSOLETO usar zone_getShippedWarehouse - * Devuelve la mínima fecha de envía para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql b/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql deleted file mode 100644 index 55f443054..000000000 --- a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql +++ /dev/null @@ -1,20 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql b/db/changes/10081-agency/04-zone_getOptionsForLanding.sql deleted file mode 100644 index ae081f14b..000000000 --- a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql +++ /dev/null @@ -1,67 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForLanding`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) -BEGIN -/** - * Gets computed options for the passed zones and delivery date. - * - * @table tmp.zones(id) The zones ids - * @param vLanded The delivery date - * @return tmp.zoneOption The computed options - */ - DECLARE vHour TIME DEFAULT TIME(NOW()); - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.travelingDays, z.travelingDays) travelingDays, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - WHERE ( - e.`type` = 'day' - AND e.dated = vLanded - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(vLanded)) - AND (e.`started` IS NULL OR vLanded >= e.`started`) - AND (e.`ended` IS NULL OR vLanded <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; - - DELETE FROM tTemp - WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() - OR @shipped = CURDATE() AND vHour > `hour`; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE tTemp; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql b/db/changes/10081-agency/04-zone_getOptionsForShipment.sql deleted file mode 100644 index c631f8809..000000000 --- a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql +++ /dev/null @@ -1,76 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForShipment`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) -BEGIN -/** - * Gets computed options for the passed zones and shipping date. - * - * @table tmp.zones(id) The zones ids - * @param vShipped The shipping date - * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options - */ - DROP TEMPORARY TABLE IF EXISTS tLandings; - CREATE TEMPORARY TABLE tLandings - (INDEX (eventFk)) - ENGINE = MEMORY - SELECT e.id eventFk, - @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, - TIMESTAMPADD(DAY, @travelingDays, vShipped) landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity, - l.travelingDays, - l.landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - JOIN tLandings l ON l.eventFk = e.id - WHERE ( - e.`type` = 'day' - AND e.`dated` = l.landed - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(l.landed)) - AND (e.`started` IS NULL OR l.landed >= e.`started`) - AND (e.`ended` IS NULL OR l.landed <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE - tTemp, - tLandings; -END$$ - -DELIMITER ; - diff --git a/db/changes/10090-iberflora/00-ACL.sql b/db/changes/10090-iberflora/00-ACL.sql deleted file mode 100644 index 3a20e3ecb..000000000 --- a/db/changes/10090-iberflora/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Claim', 'updateClaimAction', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'); diff --git a/db/changes/10090-iberflora/00-claimState.sql b/db/changes/10090-iberflora/00-claimState.sql deleted file mode 100644 index 7a964979b..000000000 --- a/db/changes/10090-iberflora/00-claimState.sql +++ /dev/null @@ -1,2 +0,0 @@ -UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '3'); -UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '5'); diff --git a/db/changes/10090-iberflora/00-component.sql b/db/changes/10090-iberflora/00-component.sql deleted file mode 100644 index fe5de47fc..000000000 --- a/db/changes/10090-iberflora/00-component.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`component` AS - SELECT - `t`.`Id_Componente` AS `id`, - `t`.`Componente` AS `name`, - `t`.`tarifa_componentes_series_id` AS `typeFk`, - `t`.`tarifa_class` AS `classRate`, - `t`.`tax` AS `tax`, - `t`.`is_renewable` AS `isRenewable`, - `t`.`code` AS `code` - FROM - `bi`.`tarifa_componentes` `t`; diff --git a/db/changes/10091-iberflora/00-department.sql b/db/changes/10091-iberflora/00-department.sql deleted file mode 100644 index 415879485..000000000 --- a/db/changes/10091-iberflora/00-department.sql +++ /dev/null @@ -1,2 +0,0 @@ - -UPDATE vn.department SET lft = NULL, rgt = NULL; diff --git a/db/changes/10091-iberflora/00-department_calcTree.sql b/db/changes/10091-iberflora/00-department_calcTree.sql deleted file mode 100644 index 5f518d2e2..000000000 --- a/db/changes/10091-iberflora/00-department_calcTree.sql +++ /dev/null @@ -1,37 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_calcTree`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`() -BEGIN -/** - * Calculates the #path, #lft, #rgt, #sons and #depth columns of - * the #department table. To build the tree, it uses the #parentFk - * column. - */ - DECLARE vIndex INT DEFAULT 0; - DECLARE vSons INT; - - DROP TEMPORARY TABLE IF EXISTS tNestedTree; - CREATE TEMPORARY TABLE tNestedTree - SELECT id, path, lft, rgt, depth, sons - FROM department LIMIT 0; - - SET max_sp_recursion_depth = 5; - CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons); - SET max_sp_recursion_depth = 0; - - UPDATE department z - JOIN tNestedTree t ON t.id = z.id - SET z.path = t.path, - z.lft = t.lft, - z.rgt = t.rgt, - z.depth = t.depth, - z.sons = t.sons; - - DROP TEMPORARY TABLE tNestedTree; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_calcTreeRec.sql b/db/changes/10091-iberflora/00-department_calcTreeRec.sql deleted file mode 100644 index 1f24270e2..000000000 --- a/db/changes/10091-iberflora/00-department_calcTreeRec.sql +++ /dev/null @@ -1,75 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_calcTreeRec`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`( - vSelf INT, - vPath VARCHAR(255), - vDepth INT, - INOUT vIndex INT, - OUT vSons INT -) -BEGIN -/** - * Calculates and sets the #path, #lft, #rgt, #sons and #depth - * columns for all children of the passed node. Once calculated - * the last node rgt index and the number of sons are returned. - * To update it's children, this procedure calls itself recursively - * for each one. - * - * @vSelf The node identifier - * @vPath The initial path - * @vDepth The initial depth - * @vIndex The initial lft index - * @vSons The number of direct sons - */ - DECLARE vChildFk INT; - DECLARE vLft INT; - DECLARE vMySons INT; - DECLARE vDone BOOL; - DECLARE vChildren CURSOR FOR - SELECT id FROM department - WHERE (vSelf IS NULL AND parentFk IS NULL) - OR (vSelf IS NOT NULL AND parentFk = vSelf); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - SET vSons = 0; - - OPEN vChildren; - myLoop: LOOP - SET vDone = FALSE; - FETCH vChildren INTO vChildFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - SET vIndex = vIndex + 1; - SET vLft = vIndex; - SET vSons = vSons + 1; - - CALL department_calcTreeRec( - vChildFk, - CONCAT(vPath, vChildFk, '/'), - vDepth + 1, - vIndex, - vMySons - ); - - SET vIndex = vIndex + 1; - - INSERT INTO tNestedTree - SET id = vChildFk, - path = vPath, - lft = vLft, - rgt = vIndex, - depth = vDepth, - sons = vMySons; - END LOOP; - CLOSE vChildren; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_doCalc.sql b/db/changes/10091-iberflora/00-department_doCalc.sql deleted file mode 100644 index ba5c16c48..000000000 --- a/db/changes/10091-iberflora/00-department_doCalc.sql +++ /dev/null @@ -1,35 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_doCalc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() -proc: BEGIN -/** - * Recalculates the department tree. - */ - DECLARE vIsChanged BOOL; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('vn.department_doCalc'); - RESIGNAL; - END; - - IF !GET_LOCK('vn.department_doCalc', 0) THEN - LEAVE proc; - END IF; - - SELECT isChanged INTO vIsChanged - FROM department_recalc; - - IF vIsChanged THEN - UPDATE department_recalc SET isChanged = FALSE; - CALL vn.department_calcTree; - END IF; - - DO RELEASE_LOCK('vn.department_doCalc'); -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_getLeaves.sql b/db/changes/10091-iberflora/00-department_getLeaves.sql deleted file mode 100644 index 436f67dbf..000000000 --- a/db/changes/10091-iberflora/00-department_getLeaves.sql +++ /dev/null @@ -1,84 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_getLeaves`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( - vParentFk INT, - vSearch VARCHAR(255) -) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id FROM department LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id FROM department - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - ENGINE = MEMORY - SELECT id FROM department LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM department g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE - tChilds, - tParents; - END IF; - - IF !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM department - WHERE parentFk <=> vParentFk; - END IF; - - SELECT d.id, - d.`name`, - d.parentFk, - d.sons - FROM department d - JOIN tNodes n ON n.id = d.id - ORDER BY depth, `name`; - - DROP TEMPORARY TABLE tNodes; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-route.sql b/db/changes/10091-iberflora/00-route.sql deleted file mode 100644 index 5d8b8de62..000000000 --- a/db/changes/10091-iberflora/00-route.sql +++ /dev/null @@ -1,10 +0,0 @@ -ALTER TABLE `vn`.`route` -ADD COLUMN `zoneFk` INT NULL AFTER `description`, -ADD INDEX `fk_route_1_idx` (`zoneFk` ASC); -; -ALTER TABLE `vn`.`route` -ADD CONSTRAINT `fk_route_1` - FOREIGN KEY (`zoneFk`) - REFERENCES `vn`.`zone` (`id`) - ON DELETE RESTRICT - ON UPDATE CASCADE; diff --git a/db/changes/10100-allSaints/00-ACL.sql b/db/changes/10100-allSaints/00-ACL.sql deleted file mode 100644 index ea1ba706b..000000000 --- a/db/changes/10100-allSaints/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/10100-allSaints/00-travelLog.sql b/db/changes/10100-allSaints/00-travelLog.sql deleted file mode 100644 index fe9d03274..000000000 --- a/db/changes/10100-allSaints/00-travelLog.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`travelLog` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `originFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text CHARACTER SET utf8, - `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `oldInstance` text COLLATE utf8_unicode_ci, - `newInstance` text COLLATE utf8_unicode_ci, - `changedModelId` int(11) DEFAULT NULL, - `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-upperGap.sql b/db/changes/10100-allSaints/00-upperGap.sql deleted file mode 100644 index 6554c47b4..000000000 --- a/db/changes/10100-allSaints/00-upperGap.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE `vn`.`packagingConfig` ( - `id` INT NOT NULL AUTO_INCREMENT, - `upperGap` INT NOT NULL, - PRIMARY KEY (`id`)); - -INSERT INTO `vn`.`packagingConfig` (`upperGap`) VALUES ('10'); diff --git a/db/changes/10100-allSaints/00-userLog.sql b/db/changes/10100-allSaints/00-userLog.sql deleted file mode 100644 index f6972796d..000000000 --- a/db/changes/10100-allSaints/00-userLog.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`userLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text CHARACTER SET utf8, - `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `oldInstance` text COLLATE utf8_unicode_ci, - `newInstance` text COLLATE utf8_unicode_ci, - `changedModelId` int(11) DEFAULT NULL, - `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-userPhoneType.sql b/db/changes/10100-allSaints/00-userPhoneType.sql deleted file mode 100644 index 6bfedcc71..000000000 --- a/db/changes/10100-allSaints/00-userPhoneType.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE `vn`.`userPhoneType` ( - `code` VARCHAR(45) NOT NULL, - `description` VARCHAR(255) NULL, - PRIMARY KEY (`code`)); - - - -INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('businessPhone', 'Telefono de empresa del usuario'); -INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('personalPhone', 'Telefono personal del usuario'); diff --git a/db/changes/10100-allSaints/01-userPhone.sql b/db/changes/10100-allSaints/01-userPhone.sql deleted file mode 100644 index 54dfbeb26..000000000 --- a/db/changes/10100-allSaints/01-userPhone.sql +++ /dev/null @@ -1,23 +0,0 @@ -CREATE TABLE `vn`.`userPhone` ( - `id` INT NOT NULL AUTO_INCREMENT, - `userFk` INT(10) UNSIGNED NOT NULL, - `typeFk` VARCHAR(45) NOT NULL, - `phone` VARCHAR(25) NOT NULL, - PRIMARY KEY (`id`), - UNIQUE INDEX `UserFk_Phone` (`userFk` ASC, `typeFk` ASC, `phone` ASC)); - - -ALTER TABLE `vn`.`userPhone` -ADD CONSTRAINT `fgnTypeFk` - FOREIGN KEY (typeFk) - REFERENCES `vn`.`userPhoneType` (code) - ON DELETE RESTRICT - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`userPhone` -ADD CONSTRAINT `fgnUserFk` - FOREIGN KEY (userFk) - REFERENCES `account`.`user` (id) - ON DELETE CASCADE - ON UPDATE CASCADE; - diff --git a/db/changes/10100-allSaints/02-ticketCalculate__.sql b/db/changes/10100-allSaints/02-ticketCalculate__.sql deleted file mode 100644 index 37903f7c3..000000000 --- a/db/changes/10100-allSaints/02-ticketCalculate__.sql +++ /dev/null @@ -1,17 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`ticketCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate__`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO utilizar catalog_calculate - CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); -END$$ - -DELIMITER ; -; diff --git a/db/changes/10100-allSaints/03-available_calc.sql b/db/changes/10100-allSaints/03-available_calc.sql deleted file mode 100644 index 70416f5df..000000000 --- a/db/changes/10100-allSaints/03-available_calc.sql +++ /dev/null @@ -1,63 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `available_calc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `available_calc`( - vDate DATE, - vAddress INT, - vAgencyMode INT) -BEGIN -/** - * Calculates the available for all available stores - * according to the given parameters. - * - * @param vDate The delivery date - * @param vAddress The delivery address id - * @param vAgencyMode The shipping agency - * @return tmp.availableCalc(calcFk) The available cache ids - */ - DECLARE vCalcFk INT; - DECLARE vShipment DATE; - DECLARE vWarehouse INT; - DECLARE vDone BOOL; - - DECLARE cWarehouses CURSOR FOR - SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - -- Establecemos los almacenes y las fechas que van a entrar al disponible - - CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); - - DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( - calcFk INT UNSIGNED, - PRIMARY KEY (calcFk) - ) - ENGINE = MEMORY; - - OPEN cWarehouses; - - l: LOOP - SET vDone = FALSE; - FETCH cWarehouses INTO vWarehouse, vShipment; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment); - - INSERT IGNORE INTO tmp.availableCalc - SET calcFk = vCalcFk; - END LOOP; - - CLOSE cWarehouses; - DROP TEMPORARY TABLE tmp.zoneGetShipped; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-catalog_calculate.sql b/db/changes/10100-allSaints/03-catalog_calculate.sql deleted file mode 100644 index e6f4f7375..000000000 --- a/db/changes/10100-allSaints/03-catalog_calculate.sql +++ /dev/null @@ -1,119 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_calculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-order_confirmWithUser.sql b/db/changes/10100-allSaints/03-order_confirmWithUser.sql deleted file mode 100644 index e7b4b2edb..000000000 --- a/db/changes/10100-allSaints/03-order_confirmWithUser.sql +++ /dev/null @@ -1,244 +0,0 @@ -USE `hedera`; -DROP procedure IF EXISTS `order_confirmWithUser`; - -DELIMITER $$ -USE `hedera`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT) -BEGIN -/** - * Confirms an order, creating each of its tickets on the corresponding - * date, store and user. - * - * @param vOrder The order identifier - * @param vUser The user identifier - */ - DECLARE vOk BOOL; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vWarehouse INT; - DECLARE vShipment DATETIME; - DECLARE vTicket INT; - DECLARE vNotes VARCHAR(255); - DECLARE vItem INT; - DECLARE vConcept VARCHAR(30); - DECLARE vAmount INT; - DECLARE vPrice DECIMAL(10,2); - DECLARE vSale INT; - DECLARE vRate INT; - DECLARE vRowId INT; - DECLARE vDelivery DATE; - DECLARE vAddress INT; - DECLARE vIsConfirmed BOOL; - DECLARE vClientId INT; - DECLARE vCompanyId INT; - DECLARE vAgencyModeId INT; - - DECLARE TICKET_FREE INT DEFAULT 2; - - DECLARE cDates CURSOR FOR - SELECT zgs.shipped, r.warehouse_id - FROM `order` o - JOIN order_row r ON r.order_id = o.id - LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id - WHERE o.id = vOrder AND r.amount != 0 - GROUP BY r.warehouse_id; - - DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate - FROM order_row r - JOIN vn.item i ON i.id = r.item_id - WHERE r.amount != 0 - AND r.warehouse_id = vWarehouse - AND r.order_id = vOrder - ORDER BY r.rate DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - -- Carga los datos del pedido - - SELECT o.date_send, o.address_id, o.note, - o.confirmed, a.clientFk, o.company_id, o.agency_id - INTO vDelivery, vAddress, vNotes, - vIsConfirmed, vClientId, vCompanyId, vAgencyModeId - FROM hedera.`order` o - JOIN vn.address a ON a.id = o.address_id - WHERE o.id = vOrder; - - -- Comprueba que el pedido no está confirmado - - IF vIsConfirmed THEN - CALL util.throw ('ORDER_ALREADY_CONFIRMED'); - END IF; - - -- Comprueba que el pedido no está vacío - - SELECT COUNT(*) > 0 INTO vOk - FROM order_row WHERE order_id = vOrder AND amount > 0; - - IF !vOk THEN - CALL util.throw ('ORDER_EMPTY'); - END IF; - - -- Carga las fechas de salida de cada almacén - - CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); - - -- Trabajador que realiza la acción - - IF vUserId IS NULL THEN - SELECT employeeFk INTO vUserId FROM orderConfig; - END IF; - - -- Crea los tickets del pedido - - START TRANSACTION; - - OPEN cDates; - - lDates: - LOOP - SET vTicket = NULL; - SET vDone = FALSE; - FETCH cDates INTO vShipment, vWarehouse; - - IF vDone THEN - LEAVE lDates; - END IF; - - -- Busca un ticket existente que coincida con los parametros - - SELECT t.id INTO vTicket - FROM vn.ticket t - LEFT JOIN vn.ticketState tls on tls.ticket = t.id - JOIN `order` o - ON o.address_id = t.addressFk - AND vWarehouse = t.warehouseFk - AND o.agency_id = t.agencyModeFk - AND o.date_send = t.landed - AND vShipment = DATE(t.shipped) - WHERE o.id = vOrder - AND t.invoiceOutFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 - LIMIT 1; - - -- Crea el ticket en el caso de no existir uno adecuado - - IF vTicket IS NULL - THEN - CALL vn.ticketCreateWithUser( - vClientId, - IFNULL(vShipment, CURDATE()), - vWarehouse, - vCompanyId, - vAddress, - vAgencyModeId, - NULL, - vDelivery, - vUserId, - vTicket - ); - ELSE - INSERT INTO vncontrol.inter - SET Id_Ticket = vTicket, - Id_Trabajador = vUserId, - state_id = TICKET_FREE; - END IF; - - INSERT IGNORE INTO vn.orderTicket - SET orderFk = vOrder, - ticketFk = vTicket; - - -- Añade las notas - - IF vNotes IS NOT NULL AND vNotes != '' - THEN - INSERT INTO vn.ticketObservation SET - ticketFk = vTicket, - observationTypeFk = 4 /* salesperson */ , - `description` = vNotes - ON DUPLICATE KEY UPDATE - `description` = CONCAT(VALUES(`description`),'. ', `description`); - END IF; - - -- Añade los movimientos y sus componentes - - OPEN cRows; - - lRows: - LOOP - SET vDone = FALSE; - FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; - - IF vDone THEN - LEAVE lRows; - END IF; - - INSERT INTO vn.sale - SET - itemFk = vItem, - ticketFk = vTicket, - concept = vConcept, - quantity = vAmount, - price = vPrice, - priceFixed = 0, - isPriceFixed = TRUE; - - SET vSale = LAST_INSERT_ID(); - - INSERT INTO vn.saleComponent - (saleFk, componentFk, `value`) - SELECT vSale, cm.component_id, cm.price - FROM order_component cm - JOIN bi.tarifa_componentes tc - ON tc.Id_Componente = cm.component_id - WHERE cm.order_row_id = vRowId - GROUP BY vSale, cm.component_id; - - UPDATE order_row SET Id_Movimiento = vSale - WHERE id = vRowId; - - END LOOP; - - CLOSE cRows; - - -- Fija el coste - - DROP TEMPORARY TABLE IF EXISTS tComponents; - CREATE TEMPORARY TABLE tComponents - (INDEX (saleFk)) - ENGINE = MEMORY - SELECT SUM(sc.`value`) valueSum, sc.saleFk - FROM vn.saleComponent sc - JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk - JOIN bi.tarifa_componentes_series tcs - ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id - AND tcs.base - JOIN vn.sale s - ON s.id = sc.saleFk - WHERE s.ticketFk = vTicket - GROUP BY sc.saleFk; - - UPDATE vn.sale s - JOIN tComponents mc ON mc.saleFk = s.id - SET s.priceFixed = valueSum; - - DROP TEMPORARY TABLE tComponents; - END LOOP; - - CLOSE cDates; - - DELETE FROM basketOrder WHERE orderFk = vOrder; - UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() - WHERE id = vOrder; - - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-ticketCalculateClon.sql b/db/changes/10100-allSaints/03-ticketCalculateClon.sql deleted file mode 100644 index 86d1c6033..000000000 --- a/db/changes/10100-allSaints/03-ticketCalculateClon.sql +++ /dev/null @@ -1,88 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCalculateClon`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) -BEGIN - /* - * @vTicketNew id del nuevo ticket clonado - * @vTicketOld id ticket original, a partir del qual se clonara el nuevo - * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo - */ - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouse SMALLINT; - DECLARE vAgencyMode INT; - DECLARE vAddress INT; - DECLARE vLanded DATE; - DECLARE vAgency INT; - DECLARE vZoneFk INT; - - REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket - WHERE ticketFk = vTicketOld; - - SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk - INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk - FROM vn.agencyMode a - JOIN vn.ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicketNew; - - IF vLanded IS NULL THEN - CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); - UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk - SET t.landed = zgl.landed, - t.zone = zgl.zoneFk - WHERE t.id = vTicketNew; - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - END IF; - - -- rellena la tabla tmp.buyUltimate con la ultima compra - CALL buyUltimate(vWarehouse, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - - CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); - - -- Bionizamos lineas con Preu = 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, vWarehouse warehouseFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; - - CALL ticketComponentUpdateSale(1); - - -- Bionizamos lineas con Preu > 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, vWarehouse warehouseFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew - AND s.price > 0; - - CALL ticketComponentUpdateSale(6); - - -- Log - CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); - - -- Limpieza - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END$$ - -DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql b/db/changes/10100-allSaints/03-ticketComponentCalculate.sql deleted file mode 100644 index 4547c4c64..000000000 --- a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql +++ /dev/null @@ -1,262 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`ticketComponentCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO usar catalog_componentCalculate -/** - * Calcula los componentes de un ticket - * - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id del modo de agencia - * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, - * packing, grouping, groupingMode, buyFk, typeFk) - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) - */ - - DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; - DECLARE vMinimumDensityWeight INT DEFAULT 167; - DECLARE vBoxFreightItem INT DEFAULT 71; - DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; - DECLARE vSpecialPriceComponent INT DEFAULT 10; - DECLARE vDeliveryComponent INT DEFAULT 15; - DECLARE vRecoveryComponent INT DEFAULT 17; - DECLARE vSellByPacketComponent INT DEFAULT 22; - DECLARE vBuyValueComponent INT DEFAULT 28; - DECLARE vMarginComponent INT DEFAULT 29; - DECLARE vDiscountLastItemComponent INT DEFAULT 32; - DECLARE vExtraBaggedComponent INT DEFAULT 38; - DECLARE vManaAutoComponent INT DEFAULT 39; - - - - SELECT volume INTO vBoxVolume - FROM vn.packaging - WHERE id = '94'; - - SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; - - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, tl.warehouseFk, tl.available, - IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, - IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, - IFNULL(pf.rate3, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk - FROM priceFixed pf - JOIN tmp.zoneGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 - WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - CREATE TEMPORARY TABLE tmp.ticketComponent ( - `warehouseFk` INT UNSIGNED NOT NULL, - `itemFk` INT NOT NULL, - `componentFk` INT UNSIGNED NOT NULL, - `cost` DECIMAL(10,4) NOT NULL, - INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), - UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vBuyValueComponent, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vMarginComponent, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - GROUP BY tc.itemFk, warehouseFk; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk - WHERE cr.recobro > 0.009; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, - tcb.itemFk, - cr.id, - GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN componentRate cr - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - vDeliveryComponent, - vGeneralInflationCoefficient - * ROUND(( - i.compression - * r.cm3 - * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) - * IFNULL((z.price - z.bonus) - * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 - ) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN agencyMode am ON am.id = vAgencyModeFk - JOIN `address` a ON a.id = vAddressFk - JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk - JOIN zone z ON z.id = zgs.id - LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk - AND r.Id_Article = tcc.itemFk - HAVING cost <> 0; - - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = vAddressFk; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN componentRate cr ON cr.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE cr.classRate IS NULL - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate - FROM tmp.ticketComponent tc - JOIN componentRate cr ON cr.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) / weightGrouping AS DECIMAL(10,2)) priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; -END$$ - -DELIMITER ; -; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql b/db/changes/10100-allSaints/03-ticketCreateWithUser.sql deleted file mode 100644 index 8135c72bf..000000000 --- a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql +++ /dev/null @@ -1,88 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithUser`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF vAgencyModeFk IS NOT NULL THEN - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - IF vZoneFk IS NULL OR vZoneFk = 0 THEN - CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); - END IF; - END IF; - INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - routeFk, - companyFk, - landed, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - vAgencyModeFk, - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql b/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql deleted file mode 100644 index b4840e31d..000000000 --- a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql +++ /dev/null @@ -1,90 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithoutZone`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - INSERT INTO vn2008.Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Agencia, - Alias, - warehouse_id, - Id_Ruta, - empresa_id, - landing, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql b/db/changes/10100-allSaints/05-catalog_calcFromItem.sql deleted file mode 100644 index 40b2c2eb8..000000000 --- a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql +++ /dev/null @@ -1,31 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_calcFromItem`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT, - vItemFk INT) -BEGIN -/** - * Calculates available and price for a single item. - * - * @param vItemFk The item id - * @return tmp.ticketCalculateItem - * @return tmp.ticketComponentPrice - * @return tmp.ticketComponent - * @return tmp.ticketLot - * @return tmp.zoneGetShipped - */ - DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY - SELECT vItemFk itemFk; - - CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); - DROP TEMPORARY TABLE tmp.item; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-chatConfig.sql b/db/changes/10110-postCampaign/00-chatConfig.sql deleted file mode 100644 index e0423bb86..000000000 --- a/db/changes/10110-postCampaign/00-chatConfig.sql +++ /dev/null @@ -1,11 +0,0 @@ -USE `vn`; - -CREATE TABLE `vn`.`chatConfig` ( - `id` INT NOT NULL AUTO_INCREMENT, - `uri` VARCHAR(255) NOT NULL, - `user` VARCHAR(50) NOT NULL, - `password` VARCHAR(50) NOT NULL, - PRIMARY KEY (`id`)); - - -INSERT INTO `vn`.`chatConfig` (`uri`, `user`, `password`) VALUES ('https://chat.verdnatura.es/api/v1', 'VnBot', 'Ub606cux7op.'); diff --git a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql b/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql deleted file mode 100644 index 5e69e28ad..000000000 --- a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql +++ /dev/null @@ -1,51 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`client_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`client_beforeUpdate` - BEFORE UPDATE ON `client` - FOR EACH ROW -BEGIN - DECLARE vText VARCHAR(255) DEFAULT NULL; - -- Comprueba que el formato de los teléfonos es válido - - IF !(NEW.phone <=> OLD.phone) THEN - CALL pbx.phone_isValid(NEW.phone); - END IF; - - IF !(NEW.mobile <=> OLD.mobile) THEN - CALL pbx.phone_isValid(NEW.mobile); - END IF; - - IF !(NEW.fax <=> OLD.fax) THEN - CALL pbx.phone_isValid(NEW.fax); - END IF; - - IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN - SET NEW.dueDay = 5; - END IF; - - -- Avisar al comercial si ha llegado la documentación sepa/core - - IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN - SET vText = 'Sepa de VNL'; - END IF; - - IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN - SET vText = 'Core de VNL'; - END IF; - - IF vText IS NOT NULL - THEN - INSERT INTO mail(sender, replyTo, `subject`, body) - SELECT - CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), - 'administracion@verdnatura.es', - CONCAT('Cliente ', NEW.id), - CONCAT('Recibida la documentación: ', vText) - FROM worker w - LEFT JOIN account.user u ON w.userFk = u.id AND u.active - LEFT JOIN account.account ac ON ac.id = u.id - WHERE w.id = NEW.salesPersonFk; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-clientGetMana.sql b/db/changes/10110-postCampaign/00-clientGetMana.sql deleted file mode 100644 index dcf9171b2..000000000 --- a/db/changes/10110-postCampaign/00-clientGetMana.sql +++ /dev/null @@ -1,75 +0,0 @@ -DROP function IF EXISTS `vn`.`clientGetMana`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`clientGetMana`(vClient INT) RETURNS decimal(10,2) - DETERMINISTIC -BEGIN -/** - * Devuelve el mana del cliente. - * - * @param vClient Id del cliente - * @return Mana del cliente - */ - DECLARE vMana DECIMAL(10,2); - DECLARE vFromDated DATE; - DECLARE vHasMana BOOLEAN; - DECLARE vManaComponent INT; - DECLARE vAutoManaComponent INT; - DECLARE vManaBank INT; - DECLARE vManaGreugeType INT; - - SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; - SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; - SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; - SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; - - SELECT COUNT(*) INTO vHasMana - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasMana THEN - RETURN 0; - END IF; - - SELECT max(dated) INTO vFromDated - FROM clientManaCache; - - SELECT sum(mana) INTO vMana - FROM - ( - SELECT mana - FROM clientManaCache - WHERE clientFk = vClient - AND dated = vFromDated - UNION ALL - SELECT s.quantity * value - FROM ticket t - JOIN address a ON a.id = t.addressFk - JOIN sale s on s.ticketFk = t.id - JOIN saleComponent sc on sc.saleFk = s.id - WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated - AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) - AND a.clientFk = vClient - UNION ALL - SELECT - amountPaid - FROM receipt r - JOIN `client` c ON c.id = r.clientFk - WHERE r.bankFk = vManaBank - AND r.payed > vFromDated - AND r.payed <= CURDATE() - AND c.id = vClient - UNION ALL - SELECT g.amount - FROM greuge g - JOIN `client` c ON c.id = g.clientFk - WHERE g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated - AND g.shipped <= CURDATE() - AND c.id = vClient - ) sub; - RETURN IFNULL(vMana,0); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql b/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql deleted file mode 100644 index a981fd5cb..000000000 --- a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql +++ /dev/null @@ -1,97 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`clientPackagingOverstock`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; - CREATE TEMPORARY TABLE tmp.clientPackagingOverstock - ENGINE = MEMORY - SELECT itemFk, - sum(GotfromClient) - sum(SenttoClient) as devueltos, - sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados, - LEAST( - sum(GotfromClient) - sum(SenttoClient), - sum(InvoicedtoClient) - sum(InvoicedfromClient) - ) as abonables - FROM - ( - SELECT t.*, - IF(@month = month, 0, 1) monthEnd, - @month := month - FROM - ( - SELECT x.id as ticketFk, - date(x.shipped) as shipped, - x.itemFk, - IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient, - IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient, - IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient, - IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient, - i.name as concept, - x.refFk as invoice, - month(shipped) month, - x.companyFk - FROM - ( - SELECT t.id, - t.shipped, - IFNULL(pe.equivalentFk, s.itemFk) itemFk, - IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient, - IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient, - NULL SenttoClient, - NULL GotfromClient, - t.refFk, - @month := 0 month, - t.companyFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk - JOIN packaging p ON p.itemFk = s.itemFk - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk - WHERE t.clientFk = vClientFk - AND t.shipped > '2017-11-30' - AND p.isPackageReturnable - UNION ALL - SELECT NULL, - '2017-11-30', - IFNULL(pe.equivalentFk, tps.itemFk) itemFk, - tps.sent InvoicedtoClient, - tps.returned InvoicedfromClient, - NULL SenttoClient, - NULL GotfromClient, - 'Histórico', - NULL, - NULL - - FROM ticketPackagingStartingStock tps - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk - WHERE tps.clientFk = vClientFk - AND tps.isForgetable = FALSE - UNION ALL - SELECT t.id, - t.shipped, - IFNULL(pe.equivalentFk, p.itemFk) itemFk, - NULL, - NULL, - IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient, - IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient, - NULL AS refFk, - NULL, - t.companyFk - FROM ticketPackaging tp - JOIN ticket t on t.id = tp.ticketFk - JOIN packaging p ON p.id = tp.packagingFk - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk - WHERE t.clientFk = vClientFk - AND t.shipped > '2017-11-21' ) x - - JOIN item i ON x.itemFk = i.id - GROUP BY x.id, x.itemFk - ) t - ORDER BY itemFk, shipped DESC - ) t2 - GROUP BY itemFk; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-clonTravelComplete.sql b/db/changes/10110-postCampaign/00-clonTravelComplete.sql deleted file mode 100644 index 9817613f4..000000000 --- a/db/changes/10110-postCampaign/00-clonTravelComplete.sql +++ /dev/null @@ -1,132 +0,0 @@ -DROP procedure IF EXISTS `vn`.`clonTravelComplete`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) -BEGIN - - DECLARE vTravelNew INT; - DECLARE vEntryNew INT; - DECLARE vDone BIT DEFAULT 0; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM entry e - JOIN travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE vRsBuy CURSOR FOR - SELECT b.* - FROM buy b - JOIN entry e - ON b.entryFk = e.id - WHERE e.travelFk = vTravelNew and b.entryFk=entryNew - ORDER BY e.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg - FROM travel - WHERE id = vTravelFk; - - SET vTravelNew = LAST_INSERT_ID(); - SET vDone = 0; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO entry (supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vTravelNew, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - - INSERT INTO buy (entryFk, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked) - SELECT vEntryNew, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked - FROM buy - WHERE entryFk = vAuxEntryFk; - - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - CLOSE vRsEntry; - COMMIT; - END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-country.sql b/db/changes/10110-postCampaign/00-country.sql deleted file mode 100644 index dcc883ab8..000000000 --- a/db/changes/10110-postCampaign/00-country.sql +++ /dev/null @@ -1,10 +0,0 @@ -USE `vn`; - -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 1); -UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 2); -UPDATE `vn`.`country` SET `ibanLength` = '22' WHERE (`id` = 3); -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 4); -UPDATE `vn`.`country` SET `ibanLength` = '18' WHERE (`id` = 5); -UPDATE `vn`.`country` SET `ibanLength` = '25' WHERE (`id` = 8); -UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 19); -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 30); diff --git a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql b/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql deleted file mode 100644 index 5ca0fd131..000000000 --- a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql +++ /dev/null @@ -1,16 +0,0 @@ - -DELIMITER $$ -DROP TRIGGER IF EXISTS `vn`.`creditClassification_BEFORE_UPDATE` $$ - - -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW -BEGIN - IF NEW.client <> OLD.client THEN - CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); - END IF; - IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE `client` c - SET creditInsurance = 0 WHERE c.id = NEW.client; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql b/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql deleted file mode 100644 index 4429b1e97..000000000 --- a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql +++ /dev/null @@ -1,13 +0,0 @@ - -DELIMITER $$ - -DROP TRIGGER IF EXISTS `vn`.`creditInsurance_AFTER_INSERT` $$ - -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW -BEGIN - UPDATE `client` c - JOIN vn.creditClassification cc ON cc.client = c.id - SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-department_doCalc.sql b/db/changes/10110-postCampaign/00-department_doCalc.sql deleted file mode 100644 index 7adeb30f0..000000000 --- a/db/changes/10110-postCampaign/00-department_doCalc.sql +++ /dev/null @@ -1,3 +0,0 @@ -USE `vn`; - -CREATE DEFINER=`root`@`%` EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql b/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql deleted file mode 100644 index 091acef43..000000000 --- a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql +++ /dev/null @@ -1,74 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`duaInvoiceInBooking`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT) -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vInvoiceFk INT; - DECLARE vASIEN BIGINT DEFAULT 0; - DECLARE vCounter INT DEFAULT 0; - - DECLARE rs CURSOR FOR - SELECT e.invoiceInFk - FROM entry e - JOIN duaEntry de ON de.entryFk = e.id - JOIN invoiceIn ii ON ii.id = e.invoiceInFk - WHERE de.duaFk = vDuaFk - AND de.customsValue - AND ii.isBooked = FALSE; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - UPDATE invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id - JOIN duaEntry de ON de.entryFk = e.id - JOIN dua d ON d.id = de.duaFk - SET ii.isBooked = TRUE, - ii.booked = IFNULL(ii.booked,d.booked), - ii.operated = IFNULL(ii.operated,d.operated), - ii.issued = IFNULL(ii.issued,d.issued), - ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), - e.isConfirmed = TRUE - WHERE d.id = vDuaFk; - - SELECT IFNULL(ASIEN,0) INTO vASIEN - FROM dua - WHERE id = vDuaFk; - - FETCH rs INTO vInvoiceFk; - - WHILE NOT done DO - - CALL invoiceInBookingMain(vInvoiceFk); - - IF vCounter > 0 OR vASIEN > 0 THEN - - UPDATE XDiario x - JOIN config c ON c.ASIEN = x.ASIEN - SET x.ASIEN = vASIEN; - - ELSE - - SELECT ASIEN INTO vASIEN FROM config; - - END IF; - - SET vCounter = vCounter + 1; - - FETCH rs INTO vInvoiceFk; - - END WHILE; - - CLOSE rs; - - UPDATE dua - SET ASIEN = vASIEN - WHERE id = vDuaFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql b/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql deleted file mode 100644 index 21b827a75..000000000 --- a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql +++ /dev/null @@ -1,17 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `getItemVisibleAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 - CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql b/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql deleted file mode 100644 index 4701e7124..000000000 --- a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql +++ /dev/null @@ -1,17 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `itemGetVisibleAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 - CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql b/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql deleted file mode 100644 index e6b6df2f9..000000000 --- a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql +++ /dev/null @@ -1,71 +0,0 @@ - -USE `vn`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - DECLARE vVisibleAltillo INT; - - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); - CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - - SELECT visible INTO vVisibleAltillo - FROM vn.itemShelvingStock - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - IF vRefresh THEN - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT vItem item_id, 0 stock, 0 visible; - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - vi.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN vn2008.tmp_item v - ON v.item_id = i.id - LEFT JOIN cache.available av - ON av.calc_id = vAvailableCalc AND av.item_id = i.id - LEFT JOIN cache.visible vi - ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id - LEFT JOIN cache.stock st - ON st.warehouse_id = vWarehouse AND st.item_id = i.id - WHERE (vItem IS NULL OR i.id = vItem); - - ELSE - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - v.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = i.id AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = i.id AND av.calc_id = vAvailableCalc - WHERE (vItem IS NULL OR i.id = vItem); - - END IF; - -END$$ - -DELIMITER ; -; diff --git a/db/changes/10110-postCampaign/00-payMethod.sql b/db/changes/10110-postCampaign/00-payMethod.sql deleted file mode 100644 index e2421ee53..000000000 --- a/db/changes/10110-postCampaign/00-payMethod.sql +++ /dev/null @@ -1,7 +0,0 @@ -USE `vn`; - -ALTER TABLE `vn`.`payMethod` -ADD COLUMN `code` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL AFTER `id`; - -UPDATE `vn`.`payMethod` SET `code` = 'bankDraft' WHERE (`id` = '4'); -UPDATE `vn`.`payMethod` SET `code` = 'card' WHERE (`id` = '5'); diff --git a/db/changes/10110-postCampaign/00-rangeDateInfo.sql b/db/changes/10110-postCampaign/00-rangeDateInfo.sql deleted file mode 100644 index 816269ef9..000000000 --- a/db/changes/10110-postCampaign/00-rangeDateInfo.sql +++ /dev/null @@ -1,41 +0,0 @@ -DROP procedure IF EXISTS `vn`.`rangeDateInfo`; - -DELIMITER $$ -CREATE PROCEDURE `vn`.`rangeDateInfo` (vStarted DATE, vEnded DATE) -BEGIN -/** - * Crea una tabla temporal con las fechas - * desde una fecha inicial a una final - * @param vStarted fecha inicial - * @param vEnded fecha final - */ - DECLARE vDated DATE DEFAULT vStarted; - - DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; - CREATE TEMPORARY TABLE tmp.rangeDate( - `dated` DATE, - `period` INT, - `month` INT, - `year` INT, - `day` INT, - `week` INT, - `yearMonth` INT - ) - ENGINE = MEMORY; - - WHILE vDated <= vEnded DO - INSERT INTO tmp.rangeDate - SET `dated` = vDated, - `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), - `month` = MONTH(vDated), - `year` = YEAR(vDated), - `day` = DAY(vDated), - `week` = WEEK(vDated, 1), - `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - - SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); - END WHILE; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-sample.sql b/db/changes/10110-postCampaign/00-sample.sql deleted file mode 100644 index 68e9d1a0f..000000000 --- a/db/changes/10110-postCampaign/00-sample.sql +++ /dev/null @@ -1,8 +0,0 @@ -USE `vn`; - -UPDATE `vn`.`sample` SET `description` = 'Bienvenida como nuevo cliente' WHERE (`id` = '12'); -UPDATE `vn`.`sample` SET `description` = 'Instalación y configuración de impresora de coronas' WHERE (`id` = '13'); -UPDATE `vn`.`sample` SET `description` = 'Solicitud de domiciliación bancaria' WHERE (`id` = '14'); -UPDATE `vn`.`sample` SET `description` = 'Aviso inicial por saldo deudor' WHERE (`id` = '15'); -UPDATE `vn`.`sample` SET `description` = 'Aviso reiterado por saldo deudor' WHERE (`id` = '16'); -UPDATE `vn`.`sample` SET `isVisible` = '0' WHERE (`id` = '17'); diff --git a/db/changes/10110-postCampaign/00-ticketClosure.sql b/db/changes/10110-postCampaign/00-ticketClosure.sql deleted file mode 100644 index 07c7ef812..000000000 --- a/db/changes/10110-postCampaign/00-ticketClosure.sql +++ /dev/null @@ -1,116 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketClosure`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`() -BEGIN -/** - * Realiza el cierre de todos los - * tickets de la table ticketClosure. - */ - DECLARE vDone BOOL; - DECLARE vClientFk INT; - DECLARE vTicketFk INT; - DECLARE vIsTaxDataChecked BOOL; - DECLARE vCompanyFk INT; - DECLARE vShipped DATE; - DECLARE vPriority INT DEFAULT 1; - DECLARE vReportDeliveryNote INT DEFAULT 1; - DECLARE vNewInvoiceId INT; - DECLARE vHasDailyInvoice BOOL; - DECLARE vWithPackage BOOL; - - DECLARE cur CURSOR FOR - SELECT ticketFk FROM tmp.ticketClosure; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - RESIGNAL; - END; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; - CREATE TEMPORARY TABLE tmp.ticketClosure2 - SELECT ticketFk FROM tmp.ticketClosure; - INSERT INTO tmp.ticketClosure - SELECT id FROM stowaway s - JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; - OPEN cur; - - proc: LOOP - SET vDone = FALSE; - - FETCH cur INTO vTicketFk; - - IF vDone THEN - LEAVE proc; - END IF; - - -- ticketClosure start - SELECT - c.id, - c.isTaxDataChecked, - t.companyFk, - t.shipped, - co.hasDailyInvoice, - w.isManaged - INTO vClientFk, - vIsTaxDataChecked, - vCompanyFk, - vShipped, - vHasDailyInvoice, - vWithPackage - FROM ticket t - JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.id = vTicketFk; - - INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) - (SELECT vTicketFk, p.id, COUNT(*) - FROM expedition e - JOIN packaging p ON p.itemFk = e.itemFk - WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable - AND vWithPackage - GROUP BY p.itemFk); - - -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) - (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 - FROM expedition e - JOIN item i ON i.id = e.itemFk - LEFT JOIN packaging p ON p.itemFk = i.id - WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 - AND getSpecialPrice(e.itemFk, vClientFk) > 0 - GROUP BY e.itemFk); - - IF(vHasDailyInvoice) THEN - - -- Facturacion rapida - CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); - -- Facturar si está contabilizado - IF vIsTaxDataChecked THEN - CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, - NULL, - vNewInvoiceId); - END IF; - ELSE - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - END IF; - - -- ticketClosure end - END LOOP; - - CLOSE cur; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-ticketRequest.sql b/db/changes/10110-postCampaign/00-ticketRequest.sql deleted file mode 100644 index cae9e09ce..000000000 --- a/db/changes/10110-postCampaign/00-ticketRequest.sql +++ /dev/null @@ -1,54 +0,0 @@ - -ALTER TABLE `vn`.`ticketRequest` -DROP FOREIGN KEY `fgnAtender`; -ALTER TABLE `vn`.`ticketRequest` -CHANGE COLUMN `atenderFk` `attenderFk` INT(11) NULL DEFAULT NULL ; -ALTER TABLE `vn`.`ticketRequest` -ADD CONSTRAINT `fgnAtender` - FOREIGN KEY (`attenderFk`) - REFERENCES `vn`.`worker` (`id`) - ON UPDATE CASCADE; - - - - -DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeInsert`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW -BEGIN - IF NEW.ticketFk IS NULL THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.requesterFk IS NULL THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; - - IF NEW.attenderFk IS NULL THEN - SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; -END$$ -DELIMITER ; - - -DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW -BEGIN - IF NEW.saleFk <> OLD.saleFk THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.salesPersonCode <> OLD.salesPersonCode THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; - - IF NEW.buyerCode <> OLD.buyerCode THEN - SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; -END$$ -DELIMITER ; - - diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql deleted file mode 100644 index 885e2998a..000000000 --- a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql +++ /dev/null @@ -1,77 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponents`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vIsTicketEditable BOOLEAN; - DECLARE vZoneFk INTEGER; - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql deleted file mode 100644 index 90d65fcc1..000000000 --- a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql +++ /dev/null @@ -1,77 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vZoneFk INTEGER; - - IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - END IF; - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql b/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql deleted file mode 100644 index c2091ff83..000000000 --- a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql +++ /dev/null @@ -1,73 +0,0 @@ -DROP function IF EXISTS `vn`.`workerTimeControl_add`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`workerTimeControl_add`( vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vDirection VARCHAR(6); - DECLARE vLastIn DATETIME; - DECLARE vDayStayMax INT; - DECLARE vHasDirectionOut INT; - DECLARE vLastInsertedId INT; - - SELECT dayStayMax INTO vDayStayMax - FROM workerTimeControlParams; - - SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; - - IF vDirection = 'out' THEN - - SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'in' - AND timed < vTimed; - - UPDATE workerTimeControl wtc - SET wtc.direction = 'middle' - WHERE userFk = vUserFk - AND direction = 'out' - AND timed BETWEEN vLastIn AND vTimed; - - ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut - FROM workerTimeControl wtc - WHERE userFk = vUserFk - AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - - UPDATE workerTimeControl wtc - SET wtc.direction = IF (vHasDirectionOut,'middle','out') - WHERE userFk = vUserFk - AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - - END IF; - END IF; - - INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) - VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - - SET vLastInsertedId = LAST_INSERT_ID(); - - CALL workerTimeControlSOWP(vUserFk, vTimed); - - RETURN vLastInsertedId; -END$$ - -DELIMITER ; - - - -DROP procedure IF EXISTS `vn`.`workerTimeControl_add`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) -BEGIN - - - SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql b/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql deleted file mode 100644 index 8e8c7471b..000000000 --- a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql +++ /dev/null @@ -1,41 +0,0 @@ -DROP procedure IF EXISTS `vn`.`timeControl_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - SET @vIsOdd := TRUE; - SET @vUser := NULL; - SET @vDated := NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - - CREATE TEMPORARY TABLE tmp.timeControlCalculate - SELECT userFk, - dated, - IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, - SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, - @timeWork / 3600 timeWorkDecimal - FROM (SELECT SUM(timeWork) timeWork, - userFk, - dated - FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), - IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), - IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), - IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), - IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, - IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, - wtc.userFk, - wtc.timed timed, - direction - FROM workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo - ORDER BY userFk, timed - ) sub - GROUP BY userFk, dated - ORDER BY userFk, dated - )sub2; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-Ordenes.sql b/db/changes/10110-postCampaign/01-Ordenes.sql deleted file mode 100644 index b2b2f7d35..000000000 --- a/db/changes/10110-postCampaign/01-Ordenes.sql +++ /dev/null @@ -1,53 +0,0 @@ - -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn2008`.`Ordenes` AS - SELECT - `tr`.`id` AS `Id_ORDEN`, - `tr`.`description` AS `ORDEN`, - `tr`.`requesterFk` AS `requesterFk`, - `tr`.`attenderFk` AS `attenderFk`, - `tr`.`quantity` AS `CANTIDAD`, - `tr`.`itemFk` AS `Id_ARTICLE`, - `tr`.`price` AS `PRECIOMAX`, - `tr`.`isOk` AS `isOk`, - `tr`.`saleFk` AS `Id_Movimiento`, - `tr`.`ticketFk` AS `ticketFk`, - `tr`.`response` AS `COMENTARIO`, - `tr`.`created` AS `odbc_date`, - `tr`.`ordered` AS `datORDEN`, - `tr`.`shipped` AS `datTICKET`, - `tr`.`salesPersonCode` AS `CodVENDEDOR`, - `tr`.`buyerCode` AS `CodCOMPRADOR`, - `tr`.`price__` AS `PREU`, - `tr`.`clientFk` AS `Id_CLIENTE`, - `tr`.`ok__` AS `OK`, - `tr`.`total` AS `TOTAL`, - `tr`.`buyed` AS `datCOMPRA`, - `tr`.`ko__` AS `KO` - FROM - `vn`.`ticketRequest` `tr`; - - -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`ticketRequest__` AS - SELECT - `t`.`Id_ORDEN` AS `id`, - `t`.`ORDEN` AS `description`, - `t`.`requesterFk` AS `requesterFk`, - `t`.`attenderFk` AS `attenderFk`, - `t`.`CANTIDAD` AS `quantity`, - `t`.`Id_ARTICLE` AS `itemFk`, - `t`.`PRECIOMAX` AS `price`, - `t`.`isOk` AS `isOk`, - `t`.`Id_Movimiento` AS `saleFk`, - `t`.`ticketFk` AS `ticketFk`, - `t`.`COMENTARIO` AS `response`, - `t`.`odbc_date` AS `created` - FROM - `vn2008`.`Ordenes` `t`; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql b/db/changes/10110-postCampaign/01-bionicCalcReverse.sql deleted file mode 100644 index e3f6b1387..000000000 --- a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql +++ /dev/null @@ -1,92 +0,0 @@ -DROP function IF EXISTS `vn`.`bionicCalcReverse`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`bionicCalcReverse`(vWarehouse INT, - vMargin DECIMAL(10,3), - vRetailedPrice DECIMAL(10,3), - vM3 DECIMAL(10,3), - vAddress INT, - vAgencyMode INT) RETURNS decimal(10,3) - DETERMINISTIC -BEGIN - DECLARE vGeneralInflationCoeficient INT; - DECLARE vVerdnaturaVolumeBox BIGINT; - DECLARE vClientFk INT; - DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; - DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; - DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; - DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; - DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; - DECLARE vComponentCostValue DECIMAL(10,2); - DECLARE vItem INT DEFAULT 98; - DECLARE vItemCarryBox INT; - - SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox - INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox - FROM bionicConfig; - - SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; - - -- Creamos la tabla tmp.bionicComponent - DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; - CREATE TEMPORARY TABLE tmp.bionicComponent( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `componentFk` int(10) unsigned NOT NULL, - `value` decimal(10,4) NOT NULL, - UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, - KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE - ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - -- Margin - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, id, vMargin - FROM component - WHERE code = vComponentMargin; - - -- Recobro - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) - FROM bi.claims_ratio cr - JOIN component c ON c.code = vComponentRecovery - WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; - - -- Componente de maná automático, en función del maná acumulado por el comercial. - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) - FROM client c - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - JOIN component co ON co.code = vComponentMana - WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; - - -- Reparto - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient - * ROUND( - vM3 - * az.price - * az.inflation - / vVerdnaturaVolumeBox, 4 - ) - FROM agencyMode ag - JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode - JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk - AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk - JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode - AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse - JOIN component co ON co.code = vComponentPort; - - -- Coste - SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue - FROM tmp.bionicComponent; - - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, id,vComponentCostValue - FROM component - WHERE code = vComponentCost; - - RETURN vComponentCostValue; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql b/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql deleted file mode 100644 index 97249bd8a..000000000 --- a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql +++ /dev/null @@ -1,96 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`timeBusiness_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - -/** - * Horas que debe trabajar un empleado según contrato y día. - * @param vDatedFrom workerTimeControl - * @param vDatedTo workerTimeControl - * @table tmp.user(userFk) - * @return tmp.timeBusinessCalculate - */ - DECLARE vHoursFullTime INT DEFAULT 40; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; - DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; - - CALL rangeDateInfo(vDatedFrom, vDatedTo); - - CREATE TEMPORARY TABLE tmp.timeBusinessCalculate - SELECT dated, - businessFk, - userFk, - departmentFk, - hourStart, - hourEnd, - timeWorkSeconds, - SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, - timeWorkSeconds / 3600 timeWorkDecimal, - timeWorkSeconds timeBusinessSeconds, - SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, - timeWorkSeconds / 3600 timeBusinessDecimal, - type, - permissionrate, - hoursWeek - FROM(SELECT rd.dated, - b.business_id businessFk, - w.userFk, - bl.department_id departmentFk, - IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart , - IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd, - IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds, - cs.type, - cs.permissionRate, - cl.hours_week hoursWeek - FROM tmp.rangeDate rd - LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) - LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id - LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id - LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id - JOIN tmp.`user` u ON u.userFK = w.userFK - JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id - LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id - LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id - LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id - LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id - LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 - LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated - LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id - WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.userFk,dated - )sub; - - - UPDATE tmp.timeBusinessCalculate t - SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600, - t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), - t.timeWorkDecimal = vHoursFullTime / 5, - t.timeBusinessSeconds = vHoursFullTime / 5 * 3600, - t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), - t.timeBusinessDecimal = vHoursFullTime / 5 - WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ; - - UPDATE tmp.timeBusinessCalculate t - SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate) , - t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)), - t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate) - WHERE permissionrate <> 0; - - UPDATE tmp.timeBusinessCalculate t - JOIN postgresql.calendar_labour cl ON cl.day = t.dated - JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id - SET t.timeWorkSeconds = 0, - t.timeWorkSexagesimal = 0, - t.timeWorkDecimal = 0, - t.permissionrate = 1, - t.type = 'Festivo' - WHERE t.type IS NULL; - -DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; -END$$ - -DELIMITER ; - diff --git a/db/changes/10120-december/00-entryBeforeUpdate.sql b/db/changes/10120-december/00-entryBeforeUpdate.sql deleted file mode 100644 index 088ea9328..000000000 --- a/db/changes/10120-december/00-entryBeforeUpdate.sql +++ /dev/null @@ -1,58 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`entry_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`entry_beforeUpdate` - BEFORE UPDATE ON `entry` - FOR EACH ROW -BEGIN - DECLARE vIsVirtual BOOL; - DECLARE vPrintedCount INT; - DECLARE vHasDistinctWarehouses BOOL; - - IF !(NEW.travelFk <=> OLD.travelFk) THEN - SELECT COUNT(*) > 0 INTO vIsVirtual - FROM entryVirtual WHERE entryFk = NEW.id; - - SELECT !(o.warehouseInFk <=> n.warehouseInFk) - OR !(o.warehouseOutFk <=> n.warehouseOutFk) - INTO vHasDistinctWarehouses - FROM travel o, travel n - WHERE o.id = OLD.travelFk - AND n.id = NEW.travelFk; - - IF vIsVirtual AND vHasDistinctWarehouses THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; - END IF; - - IF NEW.travelFk IS NULL THEN - SELECT COUNT(*) INTO vPrintedCount - FROM buy - WHERE entryFk = OLD.id - AND printedStickers > 0; - - IF vPrintedCount > 0 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted'; - END IF; - END IF; - END IF; - - IF !(NEW.supplierFk <=> OLD.supplierFk) THEN - SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); - END IF; - - IF !(NEW.travelFk <=> OLD.travelFk) - OR !(NEW.currencyFk <=> OLD.currencyFk) THEN - SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); - END IF; - - IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN - INSERT INTO entryLog SET - action = 'update', - description = 'Cambia a Contabilizada', - userFk = myWorker_getId(), - originFk = NEW.id; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10120-december/00-tpvTransaction.sql b/db/changes/10120-december/00-tpvTransaction.sql deleted file mode 100644 index 10ec8082c..000000000 --- a/db/changes/10120-december/00-tpvTransaction.sql +++ /dev/null @@ -1,120 +0,0 @@ - -DROP procedure IF EXISTS `hedera`.`tpvTransaction_confirm`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_confirm`( - vAmount INT - ,vOrder INT - ,vMerchant INT - ,vCurrency INT - ,vResponse INT - ,vErrorCode VARCHAR(10) -) -BEGIN -/** - * Confirma una transacción previamente iniciada, reescribiendo - * sus datos por los confirmados por el banco (solo si estos difieren). - * Genera el recibo y su correspondiente entrada en caja. - * - * @param vAmount Cantidad confirmada - * @param vOrder Identificador de transacción - * @param vMerchant Identificador de comercio - * @param vCurrency Identificador de moneda - * @param vResponse Identificador de respuesta del banco - * @param vErrorCode Código de error del banco, si lo hubiera - */ - DECLARE vReceipt INT; - DECLARE vStatus VARCHAR(10); - DECLARE vCustomer INT; - DECLARE vBank INT; - DECLARE vCompany INT; - DECLARE vEmployee INT; - DECLARE vIsDuplicated BOOLEAN; - DECLARE vDate DATE; - DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web'; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT COUNT(*) > 0 INTO vIsDuplicated - FROM tpvTransaction - WHERE id = vOrder AND response IS NOT NULL - FOR UPDATE; - - IF vIsDuplicated - THEN - CALL util.throw ('TRANSACTION_DUPLICATED'); - END IF; - - IF vResponse BETWEEN 0 AND 99 - THEN - SELECT - t.clientFk - ,m.bankFk - ,m.companyFk - ,c.employeeFk - ,DATE(t.created) - INTO - vCustomer - ,vBank - ,vCompany - ,vEmployee - ,vDate - FROM tpvMerchant m - JOIN tpvConfig c - LEFT JOIN tpvTransaction t ON t.id = vOrder - WHERE m.id = vMerchant; - - INSERT INTO vn.receipt - SET - amountPaid = vAmount / 100 - ,payed = vDate - ,workerFk = vEmployee - ,bankFk = vBank - ,clientFk = vCustomer - ,companyFk = vCompany - ,invoiceFk = vConcept - ,isConciliate = TRUE; - - SET vReceipt = LAST_INSERT_ID(); - SET vStatus = 'ok'; - - -- Código redundante - - DO vn.till_new - ( - vCustomer - ,vBank - ,vAmount / 100 - ,vConcept - ,vDate - ,'A' - ,TRUE - ,vCustomer - ,vCompany - ,vEmployee - ); - ELSE - SET vReceipt = NULL; - SET vStatus = 'ko'; - END IF; - - UPDATE tpvTransaction - SET - merchantFk = vMerchant - ,receiptFk = vReceipt - ,amount = vAmount - ,response = vResponse - ,errorCode = vErrorCode - ,status = vStatus - WHERE id = vOrder; - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10120-december/00-tpvTransaction_undo.sql b/db/changes/10120-december/00-tpvTransaction_undo.sql deleted file mode 100644 index ee7bcc5d1..000000000 --- a/db/changes/10120-december/00-tpvTransaction_undo.sql +++ /dev/null @@ -1,86 +0,0 @@ - -DROP procedure IF EXISTS `hedera`.`tpvTransaction_undo`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_undo`(vSelf INT) -BEGIN - DECLARE vCustomer INT; - DECLARE vAmount DOUBLE; - DECLARE vReceipt INT; - DECLARE vDate DATE; - DECLARE vBank INT; - DECLARE vAccount VARCHAR(12); - DECLARE vSubaccount VARCHAR(12); - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT - t.clientFk - ,t.amount / 100 - ,t.receiptFk - ,DATE(t.created) - ,m.bankFk - INTO - vCustomer - ,vAmount - ,vReceipt - ,vDate - ,vBank - FROM tpvTransaction t - JOIN tpvMerchant m ON m.id = t.merchantFk - JOIN tpvConfig c - WHERE t.id = vSelf - FOR UPDATE; - - -- Elimina el recibo - - DELETE FROM vn.receipt - WHERE id = vReceipt LIMIT 1; - - -- Elimina la entrada de cajas - - DELETE FROM vn.till - WHERE bankFk = vBank - AND DATE(dated) = vDate - AND `in` = vAmount - LIMIT 1; - - -- Elimina los asientos contables - - SELECT accountingAccount INTO vSubaccount - FROM vn.`client` WHERE id = vCustomer; - - SELECT account INTO vAccount - FROM vn.bank WHERE id = vBank; - - DELETE FROM vn.XDiario - WHERE SUBCTA = vSubaccount - AND CONTRA = vAccount - AND DATE(FECHA) = vDate - AND EUROHABER = vAmount - LIMIT 1; - - DELETE FROM vn.XDiario - WHERE CONTRA = vSubaccount - AND SUBCTA = vAccount - AND DATE(FECHA) = vDate - AND EURODEBE = vAmount - LIMIT 1; - - -- Actualiza la transaccion - - UPDATE tpvTransaction - SET response = NULL, status = 'started' - WHERE id = vSelf; - - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql b/db/changes/10130-christmas/00-catalog_componentCalculate.sql similarity index 96% rename from db/changes/10100-allSaints/02-catalog_componentCalculate.sql rename to db/changes/10130-christmas/00-catalog_componentCalculate.sql index 9d4df64c9..6eb30bbfd 100644 --- a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql +++ b/db/changes/10130-christmas/00-catalog_componentCalculate.sql @@ -1,9 +1,7 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_componentCalculate`; +DROP procedure IF EXISTS `vn`.`catalog_componentCalculate`; DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_componentCalculate`( vZoneFk INT, vAddressFk INT, vShipped DATE) @@ -19,7 +17,6 @@ proc: BEGIN * packing, grouping, groupingMode, buyFk, typeFk) * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) */ - DECLARE vClientFk INT; DECLARE vGeneralInflationCoefficient INT DEFAULT 1; DECLARE vMinimumDensityWeight INT DEFAULT 167; @@ -118,11 +115,11 @@ proc: BEGIN WHERE cr.recobro > 0.009; INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - WHERE ms.prices_modifier_activated + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + WHERE wm.isPricesModifierActivated HAVING manaAuto <> 0; INSERT INTO tmp.ticketComponent @@ -254,6 +251,4 @@ proc: BEGIN tmp.ticketComponentRate, tmp.ticketComponentCopy; END$$ - -DELIMITER ; - +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10130-christmas/00-chatConfig.sql b/db/changes/10130-christmas/00-chatConfig.sql new file mode 100644 index 000000000..beff3bde4 --- /dev/null +++ b/db/changes/10130-christmas/00-chatConfig.sql @@ -0,0 +1,5 @@ +ALTER TABLE `vn`.`chatConfig` +ADD COLUMN `host` VARCHAR(255) NOT NULL AFTER `id`, +CHANGE COLUMN `uri` `api` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL ; + +UPDATE `vn`.`chatConfig` SET `host` = 'https://chat.verdnatura.es' WHERE (`id` = '1'); diff --git a/db/changes/10130-christmas/00-greugeConfig.sql b/db/changes/10130-christmas/00-greugeConfig.sql new file mode 100644 index 000000000..c21751f08 --- /dev/null +++ b/db/changes/10130-christmas/00-greugeConfig.sql @@ -0,0 +1,6 @@ +CREATE TABLE `vn`.`greugeConfig` ( + `id` INT NOT NULL AUTO_INCREMENT, + `freightPickUpPrice` DECIMAL(10,2) NOT NULL, + PRIMARY KEY (`id`)); + +INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); diff --git a/db/changes/10130-christmas/00-manaSpellersRequery.sql b/db/changes/10130-christmas/00-manaSpellersRequery.sql new file mode 100644 index 000000000..cc185fdba --- /dev/null +++ b/db/changes/10130-christmas/00-manaSpellersRequery.sql @@ -0,0 +1,70 @@ + +DROP procedure IF EXISTS `vn`.`manaSpellersRequery`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER) +BEGIN + + DECLARE vWorkerIsExcluded BOOLEAN; + DECLARE vFromDated DATE; + DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE()); + DECLARE vMana INT; + DECLARE vAutoMana INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vMana + FROM `component` WHERE code = 'mana'; + + SELECT id INTO vAutoMana + FROM `component` WHERE code = 'autoMana'; + + SELECT id INTO vManaBank + FROM `bank` WHERE code = 'mana'; + + SELECT id INTO vManaGreugeType + FROM `greugeType` WHERE code = 'mana'; + + SELECT COUNT(*) INTO vWorkerIsExcluded + FROM workerManaExcluded + WHERE workerFk = vWorkerFk; + + IF NOT vWorkerIsExcluded THEN + + SELECT max(dated) INTO vFromDated + FROM clientManaCache; + + REPLACE workerMana (workerFk, amount) + SELECT vWorkerFk, sum(mana) FROM + ( + SELECT s.quantity * sc.value as mana + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN client c ON c.id = a.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana) + AND t.shipped > vFromDated AND t.shipped < vToDated + UNION ALL + SELECT - r.amountPaid + FROM receipt r + JOIN client c ON c.id = r.clientFk + WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank + AND payed > vFromDated + UNION ALL + SELECT g.amount + 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 < CURDATE() + UNION ALL + SELECT cc.mana + FROM clientManaCache cc + JOIN client c ON c.id = cc.clientFk + WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated + ) sub; + END IF; +END$$ + +DELIMITER ; + diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 05171dbfa..e9b5af23b 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -23,7 +23,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10080',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10120',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -36,7 +36,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `account`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -94,7 +94,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `salix`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -119,7 +119,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -142,7 +142,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `vn`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -287,7 +287,7 @@ UNLOCK TABLES; LOCK TABLES `state` WRITE; /*!40000 ALTER TABLE `state` DISABLE KEYS */; -INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0),(3,'OK',3,0,'OK',3,28,1,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1),(9,'Encajando',9,1,'PACKING',NULL,9,0,1),(10,'Encajado',10,2,'PACKED',NULL,10,0,1),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0,0),(3,'OK',3,0,'OK',3,28,1,0,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0),(9,'Encajando',9,1,'PACKING',NULL,9,0,1,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -297,7 +297,7 @@ UNLOCK TABLES; LOCK TABLES `sample` WRITE; /*!40000 ALTER TABLE `sample` DISABLE KEYS */; -INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Email de bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Email de instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Email de solicitud de datos bancarios core',1,'1'),(15,'letter-debtor-st','Email de aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Email de aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',1,'1'); +INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Solicitud de domiciliación bancaria',1,'1'),(15,'letter-debtor-st','Aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',0,'1'); /*!40000 ALTER TABLE `sample` ENABLE KEYS */; UNLOCK TABLES; @@ -307,7 +307,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,'VERDNATURA',1,78,763,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(22,'COMPRAS',65,66,NULL,72,596,2,5,0,0,1,0,NULL,NULL),(23,'CAMARA',41,42,NULL,72,604,2,6,1,0,0,0,NULL,NULL),(31,'INFORMATICA',11,12,NULL,72,127,3,9,0,0,0,0,NULL,NULL),(34,'CONTABILIDAD',4,5,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(35,'FINANZAS',6,7,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(36,'LABORAL',8,9,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,0,NULL,NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,0,0,NULL,NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,0,0,NULL,NULL),(41,'ADMINISTRACION',3,10,NULL,72,599,3,8,0,0,0,0,NULL,NULL),(43,'VENTAS',51,64,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(44,'GERENCIA',2,25,NULL,72,300,2,7,0,0,0,0,NULL,NULL),(45,'LOGISTICA',26,37,NULL,72,596,3,19,0,0,0,0,NULL,NULL),(46,'REPARTO',38,39,NULL,72,659,3,10,0,0,0,0,NULL,NULL),(48,'ALMACENAJE',40,47,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(49,'PROPIEDAD',48,75,NULL,72,1008,1,1,0,0,0,0,NULL,NULL),(52,'CARGA AEREA',27,28,NULL,72,163,4,28,0,0,0,0,NULL,NULL),(53,'MARKETING Y COMUNICACIÓN',60,61,NULL,72,1238,0,0,0,0,0,0,NULL,NULL),(54,'ORNAMENTALES',76,77,NULL,72,433,3,21,0,0,0,0,NULL,NULL),(55,'TALLER NATURAL',68,69,NULL,72,695,2,23,0,0,0,0,NULL,NULL),(56,'TALLER ARTIFICIAL',70,71,NULL,72,1780,2,24,0,0,0,0,NULL,NULL),(58,'CAMPOS',73,74,NULL,72,225,2,2,0,0,0,0,NULL,NULL),(59,'MANTENIMIENTO',49,50,NULL,72,1907,4,16,0,0,0,0,NULL,NULL),(60,'RECLAMACIONES',58,59,NULL,72,563,3,20,0,0,0,0,NULL,NULL),(61,'VNH',35,36,NULL,73,1297,3,17,0,0,0,0,NULL,NULL),(63,'VENTAS FRANCIA',62,63,NULL,72,277,2,27,0,0,0,0,NULL,NULL),(66,'VERDNAMADRID',31,32,NULL,72,163,3,18,0,0,0,0,NULL,NULL),(68,'COMPLEMENTOS',43,44,NULL,72,617,3,26,1,0,0,0,NULL,NULL),(69,'VERDNABARNA',33,34,NULL,74,432,3,22,0,0,0,0,NULL,NULL),(77,'PALETIZADO',18,19,NULL,72,230,4,15,1,0,0,0,NULL,NULL),(80,'EQUIPO J VALLES',56,57,NULL,72,693,3,4,0,0,0,0,NULL,NULL),(86,'LIMPIEZA',13,14,NULL,72,599,0,0,0,0,0,0,NULL,NULL),(89,'COORDINACION',16,17,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(90,'TRAILER',29,30,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(91,'ARTIFICIAL',45,46,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(93,'CONFECCION',67,72,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(94,'EQUIPO J BROCAL',52,53,NULL,0,NULL,NULL,NULL,0,0,1,0,NULL,NULL); +INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/'),(23,'CAMARA',5,6,NULL,72,604,2,6,1,0,0,0,NULL,'/'),(31,'INFORMATICA',7,8,NULL,72,127,3,9,0,0,0,0,NULL,'/'),(34,'CONTABILIDAD',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(35,'FINANZAS',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(36,'LABORAL',13,14,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,4,NULL,'/'),(38,'SACADO',16,17,NULL,72,230,4,14,1,0,1,0,37,'/37/'),(39,'ENCAJADO',18,19,NULL,72,230,4,12,1,0,1,0,37,'/37/'),(41,'ADMINISTRACION',25,26,NULL,72,599,3,8,0,0,0,0,NULL,'/'),(43,'VENTAS',27,38,NULL,0,NULL,NULL,NULL,0,0,0,5,NULL,'/'),(44,'GERENCIA',39,40,NULL,72,300,2,7,0,0,0,0,NULL,'/'),(45,'LOGISTICA',41,42,NULL,72,596,3,19,0,0,0,0,NULL,'/'),(46,'REPARTO',20,21,NULL,72,659,3,10,0,0,1,0,37,'/37/'),(48,'ALMACENAJE',43,44,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(49,'PROPIEDAD',45,46,NULL,72,1008,1,1,0,0,0,0,NULL,'/'),(52,'CARGA AEREA',47,48,NULL,72,163,4,28,0,0,0,0,NULL,'/'),(53,'MARKETING Y COMUNICACIÓN',49,50,NULL,72,1238,0,0,0,0,0,0,NULL,'/'),(54,'ORNAMENTALES',51,52,NULL,72,433,3,21,0,0,0,0,NULL,'/'),(55,'TALLER NATURAL',53,54,NULL,72,695,2,23,0,0,0,0,NULL,'/'),(56,'TALLER ARTIFICIAL',55,56,NULL,72,1780,2,24,0,0,0,0,NULL,'/'),(58,'CAMPOS',57,58,NULL,72,225,2,2,0,0,0,0,NULL,'/'),(59,'MANTENIMIENTO',59,60,NULL,72,1907,4,16,0,0,0,0,NULL,'/'),(60,'RECLAMACIONES',61,62,NULL,72,563,3,20,0,0,0,0,NULL,'/'),(61,'VNH',63,64,NULL,73,1297,3,17,0,0,0,0,NULL,'/'),(63,'VENTAS FRANCIA',28,29,NULL,72,277,2,27,0,0,1,0,43,'/43/'),(66,'VERDNAMADRID',65,66,NULL,72,163,3,18,0,0,0,0,NULL,'/'),(68,'COMPLEMENTOS',67,68,NULL,72,617,3,26,1,0,0,0,NULL,'/'),(69,'VERDNABARNA',69,70,NULL,74,432,3,22,0,0,0,0,NULL,'/'),(77,'PALETIZADO',22,23,NULL,72,230,4,15,1,0,1,0,37,'/37/'),(80,'EQUIPO J VALLES',30,31,NULL,72,693,3,4,0,0,1,0,43,'/43/'),(86,'LIMPIEZA',71,72,NULL,72,599,0,0,0,0,0,0,NULL,'/'),(89,'COORDINACION',73,74,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/'),(90,'TRAILER',75,76,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(91,'ARTIFICIAL',77,78,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/'),(92,'EQUIPO SILVERIO',32,33,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'),(93,'CONFECCION',79,80,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(94,'EQUIPO J BROCAL',34,35,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'),(95,'EQUIPO C ZAMBRANO',36,37,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -320,7 +320,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `bi`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -368,7 +368,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `cache`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -406,7 +406,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:15 USE `hedera`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -464,7 +464,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:58 +-- Dump completed on 2019-12-20 11:02:15 USE `postgresql`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -552,4 +552,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:58 +-- Dump completed on 2019-12-20 11:02:15 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b57575e02..a10b2003c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -20,6 +20,18 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo VALUES (1.30, 167.00, 138000, 71); +INSERT INTO `vn`.`chatConfig` (`host`, `api`) + VALUES + ('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1'); + +INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) + VALUES + ('1', '11'); + +INSERT INTO `vn`.`packagingConfig`(`upperGap`) + VALUES + ('10'); + UPDATE `account`.`role` SET id = 100 WHERE id = 0; INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `password`,`role`,`active`,`email`, `lang`) @@ -205,23 +217,23 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) (4, 'GCN Channel'), (5, 'The Newspaper'); -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) VALUES - (101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'Evil hideout', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1), - (107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), - (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), - (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), - (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1), - (111, 'Missing', NULL, 'Missing man', 'Anton', 'The space', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1), - (112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1); + (101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 333333333, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street', 'Silla', 46460, 333333333, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street', 'Silla', 46460, 333333333, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point', 'Silla', 46460, 333333333, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 333333333, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), + (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'Evil hideout', 'Silla', 46460, 333333333, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1), + (107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill', 'Silla', 46460, 333333333, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), + (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 333333333, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), + (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 333333333, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), + (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 333333333, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1), + (111, 'Missing', NULL, 'Missing man', 'Anton', 'The space', 'Silla', 46460, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1), + (112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city', 'Silla', 46460, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1); -INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `phone`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) - SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'SILLA', 46460, 623111111, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, CURDATE(), 1 +INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) + SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'SILLA', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, CURDATE(), 1 FROM `account`.`role` `r` WHERE `r`.`hasLogin` = 1; @@ -586,7 +598,8 @@ INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) (3, 'Mana', 'mana'), (4, 'Reclaim', 'reclaim'), (5, 'Heritage', 'heritage'), - (6, 'Miscellaneous', 'miscellaneous'); + (6, 'Miscellaneous', 'miscellaneous'), + (7, 'Freight Pickup', 'freightPickUp'); INSERT INTO `vn`.`greuge`(`id`, `clientFk`, `description`, `amount`, `shipped`, `created`, `greugeTypeFk`, `ticketFk`) VALUES @@ -1913,6 +1926,11 @@ INSERT INTO `vn`.`queuePriority`(`id`, `priority`) (2, 'Normal'), (3, 'Baja'); +INSERT INTO `vn`.`userPhoneType` (`code`, `description`) + VALUES + ('businessPhone', 'Telefono de empresa del usuario'), + ('personalPhone', 'Telefono personal del usuario'); + INSERT INTO `vn`.`userPhone`(`id`, `userFk`, `typeFk`, `phone`) VALUES (1, 101, 'personalPhone', 1111111111), @@ -1979,3 +1997,4 @@ INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `week VALUES (1, 43200, 129600, 734400, 43200, 50400); +INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3554c9db6..c56b2a0a1 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -4845,3456 +4845,6 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; --- --- Current Database: `bs` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `bs`; - --- --- Temporary table structure for view `bajasLaborales` --- - -DROP TABLE IF EXISTS `bajasLaborales`; -/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `bajasLaborales` AS SELECT - 1 AS `firstname`, - 1 AS `name`, - 1 AS `business_id`, - 1 AS `lastDate`, - 1 AS `endContract`, - 1 AS `type`, - 1 AS `dias`, - 1 AS `userFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `bancos_evolution` --- - -DROP TABLE IF EXISTS `bancos_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bancos_evolution` ( - `Fecha` date NOT NULL, - `Id_Banco` int(11) NOT NULL, - `saldo` double NOT NULL DEFAULT '0', - `quilla` double NOT NULL DEFAULT '0', - `deuda` double NOT NULL DEFAULT '0', - `liquidez` double NOT NULL DEFAULT '0', - `disponibilidad ajena` double NOT NULL DEFAULT '0', - `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas', - PRIMARY KEY (`Fecha`,`Id_Banco`), - KEY `fk_banco_evolution_idx` (`Id_Banco`), - CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn`.`bank` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `carteras` --- - -DROP TABLE IF EXISTS `carteras`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `carteras` ( - `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL, - `Año` int(11) NOT NULL, - `Mes` int(11) NOT NULL, - `Peso` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientDied` --- - -DROP TABLE IF EXISTS `clientDied`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientDied` ( - `id` int(11) NOT NULL DEFAULT '0', - `clientName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `lastInvoiced` date DEFAULT NULL, - `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientNewBorn` --- - -DROP TABLE IF EXISTS `clientNewBorn`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientNewBorn` ( - `clientFk` int(11) NOT NULL, - `shipped` date NOT NULL, - PRIMARY KEY (`clientFk`), - CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores` --- - -DROP TABLE IF EXISTS `compradores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `semana` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`semana`), - CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores_evolution` --- - -DROP TABLE IF EXISTS `compradores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores_evolution` ( - `Id_Trabajador` int(11) NOT NULL, - `fecha` date NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`fecha`), - CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `experienceIberflora2016` --- - -DROP TABLE IF EXISTS `experienceIberflora2016`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `experienceIberflora2016` ( - `Id_Cliente` int(11) NOT NULL, - `isVisitor` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `fondo_maniobra` --- - -DROP TABLE IF EXISTS `fondo_maniobra`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `fondo_maniobra` ( - `fecha` date NOT NULL, - `fondo` double DEFAULT NULL, - `clientes_facturas` double DEFAULT NULL, - `clientes_cobros` double DEFAULT NULL, - `proveedores_facturas` double DEFAULT NULL, - `proveedores_pagos` double DEFAULT NULL, - `fondo_medio` double DEFAULT NULL, - PRIMARY KEY (`fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `indicators` --- - -DROP TABLE IF EXISTS `indicators`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `indicators` ( - `updated` date NOT NULL, - `lastYearSales` int(11) DEFAULT NULL, - `totalGreuge` int(11) DEFAULT NULL, - `latePaymentRate` decimal(5,4) DEFAULT NULL, - `countEmployee` decimal(10,2) DEFAULT NULL, - `averageMana` int(11) DEFAULT NULL, - `bankingPool` int(11) DEFAULT NULL, - `lastMonthActiveClients` int(11) DEFAULT NULL, - `lastMonthLostClients` int(11) DEFAULT NULL, - `lastMonthNewClients` int(11) DEFAULT NULL, - `lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL, - `productionHours` decimal(10,1) DEFAULT NULL, - `dailyWorkersCost` decimal(10,0) DEFAULT NULL, - `volumeM3` decimal(10,0) DEFAULT NULL, - `salesValue` decimal(10,0) DEFAULT NULL, - `valueM3` decimal(10,0) DEFAULT NULL, - `hoursM3` decimal(5,2) DEFAULT NULL, - `workerCostM3` decimal(10,1) DEFAULT NULL, - `salesWorkersCostRate` decimal(10,2) DEFAULT NULL, - `thisWeekSales` decimal(10,2) DEFAULT NULL, - `lastYearWeekSales` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`updated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `lastIndicators` --- - -DROP TABLE IF EXISTS `lastIndicators`; -/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `lastIndicators` AS SELECT - 1 AS `updated`, - 1 AS `lastYearSales`, - 1 AS `incLastYearSales`, - 1 AS `totalGreuge`, - 1 AS `incTotalGreuge`, - 1 AS `latePaymentRate`, - 1 AS `incLatePaymentRate`, - 1 AS `countEmployee`, - 1 AS `incCountEmployee`, - 1 AS `averageMana`, - 1 AS `incAverageMana`, - 1 AS `bankingPool`, - 1 AS `incbankingPool`, - 1 AS `lastMonthActiveClients`, - 1 AS `incLastMonthActiveClients`, - 1 AS `lastMonthLostClients`, - 1 AS `incLastMonthLostClients`, - 1 AS `lastMonthNewClients`, - 1 AS `incLastMonthNewClients`, - 1 AS `lastMonthWebBuyingRate`, - 1 AS `incLastMonthWebBuyingRate`, - 1 AS `productionHours`, - 1 AS `dailyWorkersCost`, - 1 AS `volumeM3`, - 1 AS `salesValue`, - 1 AS `valueM3`, - 1 AS `hoursM3`, - 1 AS `workerCostM3`, - 1 AS `salesWorkersCostRate`, - 1 AS `thisWeekSales`, - 1 AS `lastYearWeekSales`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `m3` --- - -DROP TABLE IF EXISTS `m3`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `m3` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `fecha` date NOT NULL, - `provinceFk` smallint(5) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0', - `m3` decimal(10,2) DEFAULT NULL, - `year` int(11) DEFAULT NULL, - `month` int(11) DEFAULT NULL, - `week` int(11) DEFAULT NULL, - `day` int(11) DEFAULT NULL, - `dayName` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `euros` decimal(10,2) DEFAULT '0.00', - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `m3Silla` --- - -DROP TABLE IF EXISTS `m3Silla`; -/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `m3Silla` AS SELECT - 1 AS `fecha`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`, - 1 AS `dayName`, - 1 AS `Volumen`, - 1 AS `Euros`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `m3analisis` --- - -DROP TABLE IF EXISTS `m3analisis`; -/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `m3analisis` AS SELECT - 1 AS `fecha`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`, - 1 AS `dayName`, - 1 AS `Volumen`, - 1 AS `Euros`, - 1 AS `Departamento`, - 1 AS `Horas`, - 1 AS `Salarios`, - 1 AS `tiempoM3`, - 1 AS `valorM3`, - 1 AS `costeLaboralM3`, - 1 AS `costeEuros`, - 1 AS `precioHora`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `manaCustomer` --- - -DROP TABLE IF EXISTS `manaCustomer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `manaCustomer` ( - `Id_Cliente` int(11) NOT NULL, - `Mana` decimal(10,0) NOT NULL DEFAULT '0', - `dated` date NOT NULL, - PRIMARY KEY (`Id_Cliente`,`dated`), - KEY `manaCustomerIdx1` (`dated`), - CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `manaSpellersExcluded` --- - -DROP TABLE IF EXISTS `manaSpellersExcluded`; -/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `manaSpellersExcluded` AS SELECT - 1 AS `workerFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `mana_spellers` --- - -DROP TABLE IF EXISTS `mana_spellers`; -/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mana_spellers` AS SELECT - 1 AS `Id_Trabajador`, - 1 AS `size`, - 1 AS `used`, - 1 AS `prices_modifier_rate`, - 1 AS `prices_modifier_activated`, - 1 AS `minRate`, - 1 AS `maxRate`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mana_spellers_excluded` --- - -DROP TABLE IF EXISTS `mana_spellers_excluded`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mana_spellers_excluded` ( - `Id_Trabajador` int(11) NOT NULL, - PRIMARY KEY (`Id_Trabajador`), - CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `mermas` --- - -DROP TABLE IF EXISTS `mermas`; -/*!50001 DROP VIEW IF EXISTS `mermas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mermas` AS SELECT - 1 AS `Comprador`, - 1 AS `Familia`, - 1 AS `Referencia`, - 1 AS `Item`, - 1 AS `Cantidad`, - 1 AS `Coste_Unitario`, - 1 AS `Importe`, - 1 AS `Cliente`, - 1 AS `ticketFk`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mermasCache` --- - -DROP TABLE IF EXISTS `mermasCache`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mermasCache` ( - `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `año` int(4) NOT NULL, - `Valor_Compra` decimal(10,0) DEFAULT NULL, - `Faltas` decimal(10,0) DEFAULT NULL, - `Basura` decimal(10,0) DEFAULT NULL, - PRIMARY KEY (`Comprador`,`año`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `nightTask` --- - -DROP TABLE IF EXISTS `nightTask`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTask` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `started` datetime DEFAULT NULL, - `finished` datetime DEFAULT NULL, - `lastFinished` datetime DEFAULT NULL, - `order` int(11) DEFAULT NULL, - `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `errorCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert` BEFORE INSERT ON `nightTask` FOR EACH ROW -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 */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate` BEFORE UPDATE ON `nightTask` FOR EACH ROW -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 */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `nightTaskConfig` --- - -DROP TABLE IF EXISTS `nightTaskConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTaskConfig` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `logMail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payMethodClient` --- - -DROP TABLE IF EXISTS `payMethodClient`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payMethodClient` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '0', - `clientFk` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `FkPayMethod_idx` (`payMethodFk`), - KEY `FkClientPayMethod_idx` (`clientFk`), - KEY `FkDateClientPayMethod` (`dated`,`clientFk`), - CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_bin; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payMethodClientEvolution` --- - -DROP TABLE IF EXISTS `payMethodClientEvolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payMethodClientEvolution` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `payMethodName` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `amountClient` int(11) NOT NULL, - `amount` decimal(10,2) NOT NULL, - `equalizationTax` decimal(10,2) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity` --- - -DROP TABLE IF EXISTS `productivity`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `hh` int(10) unsigned NOT NULL, - `mm` int(10) unsigned NOT NULL, - `m3` double NOT NULL DEFAULT '0', - `workers` int(11) NOT NULL DEFAULT '0', - `wCost` double NOT NULL DEFAULT '0', - `numCoordinadores` int(11) NOT NULL DEFAULT '0', - `costCoordinacion` double NOT NULL DEFAULT '0', - `numSacadores` int(11) NOT NULL DEFAULT '0', - `costSacado` double NOT NULL DEFAULT '0', - `numEncajadores` int(11) NOT NULL DEFAULT '0', - `costEncajado` double NOT NULL DEFAULT '0', - `numPaletizadores` int(11) NOT NULL DEFAULT '0', - `costPaletizado` double NOT NULL DEFAULT '0', - `numCamareros` int(11) NOT NULL DEFAULT '0', - `costCamara` double NOT NULL DEFAULT '0', - `numComplementos` int(11) NOT NULL DEFAULT '0', - `costComplementos` double NOT NULL DEFAULT '0', - `numArtificial` int(11) NOT NULL DEFAULT '0', - `costArtificial` double NOT NULL DEFAULT '0', - `m3FV` double NOT NULL DEFAULT '0', - `m3PCA` double NOT NULL DEFAULT '0', - `m3Artificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivityDepartment` --- - -DROP TABLE IF EXISTS `productivityDepartment`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivityDepartment` ( - `dated` date NOT NULL, - `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity_evolution` --- - -DROP TABLE IF EXISTS `productivity_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity_evolution` ( - `dated` date NOT NULL, - `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salaries2018` --- - -DROP TABLE IF EXISTS `salaries2018`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salaries2018` ( - `person_id` int(11) NOT NULL DEFAULT '0', - `sex` enum('M','F') CHARACTER SET utf8 NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', - `edad` int(6) DEFAULT NULL, - `antiguedad` int(6) DEFAULT NULL, - `Modalidad` varchar(22) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', - `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `worker` varchar(82) CHARACTER SET utf8 DEFAULT NULL, - `totalDays` decimal(32,0) DEFAULT NULL, - `totalAnual` decimal(16,0) DEFAULT NULL, - `virtualMonthlySalary` decimal(16,0) DEFAULT NULL, - `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `category_name` varchar(50) CHARACTER SET utf8 NOT NULL, - `level_name` varchar(5) CHARACTER SET utf8 DEFAULT NULL, - `thisYearDateStart` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL, - PRIMARY KEY (`person_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salePersonEvolution` --- - -DROP TABLE IF EXISTS `salePersonEvolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salePersonEvolution` ( - `dated` date NOT NULL DEFAULT '0000-00-00', - `amount` decimal(10,2) NOT NULL DEFAULT '0.00', - `equalizationTax` decimal(10,2) NOT NULL DEFAULT '0.00', - `salesPersonFk` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`dated`,`salesPersonFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salesByWeek` --- - -DROP TABLE IF EXISTS `salesByWeek`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salesByWeek` ( - `week` int(11) NOT NULL, - `year` int(11) NOT NULL, - `sales` double DEFAULT NULL, - UNIQUE KEY `week` (`week`,`year`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores` --- - -DROP TABLE IF EXISTS `vendedores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `mes` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionNuevos` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), - CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores_evolution` --- - -DROP TABLE IF EXISTS `vendedores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores_evolution` ( - `workerFk` int(11) NOT NULL, - `year` int(11) NOT NULL, - `sales` decimal(10,2) DEFAULT NULL, - `month` int(11) NOT NULL, - PRIMARY KEY (`workerFk`,`year`,`month`), - CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas` --- - -DROP TABLE IF EXISTS `ventas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas` ( - `Id_Movimiento` int(11) NOT NULL, - `importe` decimal(10,3) NOT NULL DEFAULT '0.000', - `recargo` decimal(10,3) NOT NULL DEFAULT '0.000', - `fecha` date NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `Id_Cliente` int(11) NOT NULL DEFAULT '1', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Id_Movimiento`), - KEY `tip_to_tip_idx` (`tipo_id`), - KEY `clientes_bs_ventas_idx` (`Id_Cliente`), - KEY `empresa_bs_ventas_idx` (`empresa_id`), - KEY `fecha_bs` (`fecha`), - CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas_contables` --- - -DROP TABLE IF EXISTS `ventas_contables`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas_contables` ( - `year` int(4) NOT NULL, - `month` int(2) NOT NULL, - `venta` decimal(10,2) DEFAULT NULL, - `grupo` int(1) NOT NULL, - `reino_id` int(10) unsigned NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `empresa_id` int(4) NOT NULL, - `gasto` varchar(10) CHARACTER SET latin1 NOT NULL, - PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouseProduction_kk` --- - -DROP TABLE IF EXISTS `warehouseProduction_kk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouseProduction_kk` ( - `fecha` date NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `m3` decimal(10,0) NOT NULL DEFAULT '0', - `labourCost` decimal(10,0) NOT NULL DEFAULT '0', - `workerHours` decimal(10,0) NOT NULL DEFAULT '0', - PRIMARY KEY (`fecha`,`warehouse_id`), - KEY `warehouseProduction_fk1_idx` (`warehouse_id`), - CONSTRAINT `warehouseProduction_fk1` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `workerMana` --- - -DROP TABLE IF EXISTS `workerMana`; -/*!50001 DROP VIEW IF EXISTS `workerMana`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerMana` AS SELECT - 1 AS `workerFk`, - 1 AS `amount`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workerSpeed` --- - -DROP TABLE IF EXISTS `workerSpeed`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerSpeed` ( - `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', - `LitrosMinuto` decimal(10,1) DEFAULT NULL, - `LitrosMinutoLastHour` decimal(10,1) DEFAULT NULL, - `lastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - PRIMARY KEY (`workerCode`,`warehouseFk`,`accion`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'bs' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `nightTask_launchAll` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'bs' --- -/*!50003 DROP FUNCTION IF EXISTS `tramo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci -BEGIN - - DECLARE vTramo VARCHAR(20); - DECLARE vHour INT; - - SET vHour = HOUR(vDateTime) ; - - SET vTramo = - CASE - WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' - WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' - END ; - -RETURN vTramo; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() -BEGIN - -DECLARE vDateStart DATE DEFAULT '2016-01-01'; -DECLARE vDateEnd DATE DEFAULT '2016-11-30'; -DECLARE vDate DATE; - -SET vDate = vDateStart; - -DELETE FROM bs.ventasComponentes; - -WHILE vDate <= vDateEnd DO - - INSERT INTO bs.ventasComponentes - SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento - WHERE v.fecha = vDate - AND empresa_id IN (442,567) - GROUP BY mc.Id_Componente; - - SET vDate = TIMESTAMPADD(DAY,1,vDate); - - IF DAY(vDate) MOD 28 = 0 THEN - - SELECT vDate; - - END IF; - -END WHILE; - - SELECT vDate; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bancos_evolution_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() -BEGIN - /* - - Inserta en la tabla bancos_evolution los saldos acumulados - - */ - - - DECLARE vCurrentDate DATE; - DECLARE vStartingDate DATE DEFAULT '2016-01-01'; - DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, CURDATE()); - - DELETE FROM bs.bancos_evolution WHERE Fecha > vStartingDate; - - SET vCurrentDate = vStartingDate; - - WHILE vCurrentDate < vMaxDate DO - - REPLACE bs.bancos_evolution( Fecha - ,Id_Banco - ,saldo) - - SELECT vCurrentDate - , Id_Banco - , sum(saldo) - - FROM - ( - - SELECT Id_Banco - ,saldo_aux as 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 - WHERE cash IN (0,3) - AND Cajafecha = vCurrentDate - AND (Serie = 'MB' OR cash = 3) - GROUP BY Id_Banco - - UNION ALL - - SELECT id_banco, - importe -- pagos futuros - FROM vn2008.pago - WHERE fecha = vCurrentDate - AND fecha >= CURDATE() - AND NOT conciliado - - UNION ALL - - SELECT Id_Banco, Entregado -- cobros futuros - FROM vn2008.Recibos - WHERE Fechacobro = vCurrentDate - AND Fechacobro > CURDATE() - - UNION ALL - - SELECT sp.Id_Banco, Importe -- saldos de la tabla prevision - FROM vn2008.Saldos_Prevision sp - JOIN vn2008.Bancos b using(Id_Banco) - WHERE cash IN (0,3) - AND Fecha = vCurrentDate - - - - )sub - GROUP BY Id_Banco; - - -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas - - UPDATE bs.bancos_evolution be - SET saldo_aux = saldo; - - -- Ahora actualizamos la quilla - UPDATE bs.bancos_evolution be - LEFT JOIN - ( - SELECT Id_Banco, - sum(importe) as quilla - FROM vn2008.Bancos_poliza - WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) - GROUP BY Id_Banco - ) sub using(Id_Banco) - SET be.quilla = sub.quilla - WHERE be.Fecha = vCurrentDate; - - - SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); - - END WHILE; - - - -- Deuda - UPDATE bs.bancos_evolution be - JOIN vn2008.Bancos using(Id_Banco) - SET be.deuda = IF(cash = 3, be.saldo_aux, 0) - , be.saldo = IF(cash = 3, 0, be.saldo_aux) - WHERE Fecha >= vStartingDate; - - - -- 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; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `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 - FROM ( - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - SUM(v.importe) AS previousAmmount, - 0 currentAmmount - 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) - AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) - GROUP BY w.id, v.Id_Cliente) - UNION ALL - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - 0 AS previousAmmount, - SUM(s.quantity * s.price) AS currentAmmount - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE t.shipped BETWEEN vDateFrom - AND vDateTo - GROUP BY w.id, c.id) - ) comparative - GROUP BY workerName, id - HAVING (previousAmmount <> 0 OR currentAmmount <> 0) - ORDER BY workerName, id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `carteras_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`() -BEGIN - -DELETE FROM bs.carteras -WHERE Año >= YEAR(CURDATE()) - 1; - -INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) -SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso -FROM vn2008.time t -JOIN bs.ventas v on t.date = v.fecha -JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente -JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador -WHERE t.year >= YEAR(CURDATE()) - 1 -GROUP BY CodigoTrabajador, Año, Mes; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`() -BEGIN - - IF DAY(CURDATE()) = 6 THEN - - SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE()); - SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE()); - SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE()); - - TRUNCATE TABLE bs.clientDied; - - INSERT INTO bs.clientDied - SELECT c.id, - c.name as clientName, - maxIssued as lastInvoiced, - w.code AS workerCode, - b.code AS Boss, - CASE - WHEN IFNULL(maxIssued,'2000-01-01') < @tercerAviso THEN 'Tercer Aviso' - WHEN maxIssued < @segundoAviso THEN 'Segundo Aviso' - WHEN maxIssued < @primerAviso THEN 'Primer Aviso' - END as Aviso - FROM vn.client c - JOIN vn.worker w ON w.id = c.salesPersonFk - JOIN vn2008.jerarquia j ON j.worker_id = w.id - JOIN vn.worker b ON b.id = j.boss_id - JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.salesPersonFk - LEFT JOIN (SELECT clientFk, max(issued) as maxIssued FROM vn.invoiceOut GROUP BY clientFk) io ON io.clientFk = c.id - WHERE (maxIssued IS NULL OR maxIssued < @primerAviso) - AND c.created < @tercerAviso; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientNewBorn_Update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientNewBorn_Update`() -BEGIN - - DECLARE fromDated DATE DEFAULT '2019-04-01'; - - -- Eliminamos clientes que ya no son nuevos - DELETE FROM bs.clientNewBorn - WHERE shipped < TIMESTAMPADD(YEAR,-1,CURDATE()); - - -- Clientes nuevos - REPLACE bs.clientNewBorn(clientFk,shipped) - SELECT t.clientFk, MIN(t.shipped) as shipped - FROM vn.ticket t - WHERE shipped > '2001-01-01' - GROUP BY t.clientFk - HAVING shipped >= GREATEST(TIMESTAMPADD(YEAR,-1,CURDATE()), fromDated); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comercialesCompleto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE) -BEGIN - -CALL vn.subordinateGetList(vWorker); - -SELECT - c.Id_Cliente id_cliente, - c.calidad, - c.Cliente cliente, - cr.recobro * 100 tarifa, - c.Telefono telefono, - c.movil, - c.POBLACION poblacion, - p.`name` provincia, - vn2008.red(f.futur) futur, - c.Credito credito, - pm.`name` forma_pago, - vn2008.red(c365 / 12) consumo_medio365, - vn2008.red(c365) consumo365, - vn2008.red(CmLy.peso) peso_mes_año_pasado, - vn2008.red(CmLy.peso * 1.19) objetivo, - tr.CodigoTrabajador, - vn2008.red(mes_actual.consumo) consumoMes, - vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, - DATE(LastTicket) ultimo_ticket, - dead.muerto, - g.Greuge, - cr.recobro -FROM - vn2008.Clientes c - LEFT JOIN - (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge - FROM vn2008.Greuges - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = c.Id_Cliente - LEFT JOIN - vn2008.province p ON p.province_id = c.province_id - JOIN - vn2008.pay_met pm ON pm.id = c.pay_met_id - LEFT JOIN - vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - LEFT JOIN - bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 - FROM bs.ventas v - JOIN vn2008.Clientes c USING (Id_Cliente) - - 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 - 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) - 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 - (SELECT - t.Id_Cliente, - SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) - GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente - LEFT JOIN - (SELECT - MAX(t.Fecha) LastTicket, c.Id_Cliente - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - SUM(importe) peso, c.Id_Cliente - FROM - bs.ventas v - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - MONTH(fecha) = MONTH(vDate) - AND YEAR(fecha) = YEAR(vDate) - 1 - AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - c.Id_Cliente, - IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto - FROM - vn2008.Facturas f - JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente - - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente - JOIN tmp.subordinate s ON s.workerFk = c.Id_Trabajador; - -DROP TEMPORARY TABLE tmp.subordinate; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT) -BEGIN - -REPLACE bs.compradores - -SELECT tp.Id_Trabajador - , intYEAR as año - , tm.week as semana - , sum(importe) as importe - , 0 as comision - -FROM bs.ventas v -JOIN vn2008.time tm on tm.date = v.fecha -JOIN vn2008.Tipos tp using(tipo_id) -WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END -AND reino_id != 6 -GROUP BY tp.Id_Trabajador, tm.week; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add_launcher`() -BEGIN - - DECLARE vYear INT; - DECLARE vWeek INT; - DECLARE done BOOL DEFAULT FALSE; - - DECLARE rs CURSOR FOR - SELECT year, week - FROM vn.time - WHERE (year = vYear AND week >= vWeek) - OR year > vYear; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear - FROM compradores; - - SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; - - OPEN rs; - - FETCH rs INTO vYear, vWeek; - - WHILE NOT done DO - - CALL compradores_add(vYear, vWeek, vWeek); - - FETCH rs INTO vYear, vWeek; - - END WHILE; - - CLOSE rs; - - CALL compradores_evolution_add; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; - - WHILE datFEC < CURDATE() DO - - SELECT datFEC; - - REPLACE bs.compradores_evolution( Id_Trabajador - , fecha - , importe) - - SELECT Id_Trabajador - , datFEC as fecha - , sum(importe) as importe - - FROM - ( - - SELECT Id_Trabajador - , 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 - GROUP BY Id_Trabajador; - - - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`() -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 FROM bs.fondo_maniobra; - - WHILE datFEC < CURDATE() DO - - -- esto solo sirve para no aburrirse mientras esperamos... - - IF day(datFEC) mod 28 = 0 then - 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(Facturas.Importe) AS Facturas - FROM vn2008.Facturas - INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <>1381 - AND Fecha between '2011-01-01' and datFEC) fac - JOIN - ( - SELECT - Sum(Entregado) AS Cobros - FROM vn2008.Recibos - INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <> 1381 - AND Fechacobro Between '2011-01-01' and datFEC) cob - JOIN - ( - SELECT - Sum(cantidad) AS Recibidas - FROM vn2008.recibida - INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id - WHERE empresa_id <> 1381 - AND recibida.fecha Between '2015-01-01' and datFEC) rec - JOIN - ( - SELECT Sum(importe) AS Pagos - FROM vn2008.pago - WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag; - - - - UPDATE bs.fondo_maniobra - JOIN - (SELECT avg(fondo) as media - FROM bs.fondo_maniobra - WHERE fecha <= datFEC) sub - SET fondo_medio = media - WHERE fecha = datFEC; - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdate`(vDated DATE) -BEGIN - - DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated); - DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated); - DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated); - DECLARE vWeek INT; - - REPLACE indicators(updated) - VALUES(vDated); - - -- Ventas totales del ultimo año - UPDATE indicators - SET lastYearSales = - ( - SELECT SUM(importe + recargo) - FROM bs.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 = - ( - 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 WHERE date = vDated and amount > 0) - / - ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) - WHERE updated = vDated; - - -- Número de trabajadores activos - UPDATE indicators - SET countEmployee = - ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) - FROM - postgresql.business AS b - JOIN postgresql.profile p ON p.profile_id = b.provider_id - JOIN postgresql.person pe ON pe.person_id = p.person_id - LEFT JOIN - postgresql.business_labour AS bl ON bl.business_id = b.business_id - LEFT JOIN - postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - WHERE - (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated)) - AND pe.name = 'VERDNATURA LEVANTE SL' - ) - WHERE updated = vDated; - - -- Maná medio acumulado por comercial - UPDATE indicators - SET averageMana = - (SELECT avg(used) - FROM bs.mana_spellers - ) - WHERE updated = vDated; - - -- Número de clientes que han comprado en los últimos 30 dias - UPDATE indicators - SET lastMonthActiveClients = - (SELECT COUNT(DISTINCT t.clientFk) - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) - WHERE updated = vDated; - - -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores - UPDATE indicators - SET lastMonthLostClients = - (SELECT COUNT(lm.clientFk) - FROM - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) cm - RIGHT JOIN - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped >= twoMonthsBefore - AND t.shipped < oneMonthBefore - ) lm ON lm.clientFk = cm.clientFk - WHERE cm.clientFk IS NULL - ) - WHERE updated = vDated; - - -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores - UPDATE indicators - SET lastMonthNewClients = - (SELECT COUNT(cm.clientFk) - FROM - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) cm - LEFT JOIN - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped >= twoMonthsBefore - AND t.shipped < oneMonthBefore - ) lm ON lm.clientFk = cm.clientFk - WHERE lm.clientFk IS NULL - ) - WHERE updated = vDated; - - -- Porcentaje de autopedidos sobre los pedidos totales - UPDATE indicators - SET lastMonthWebBuyingRate = - ( SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '') - FROM hedera.`order` - WHERE date_send BETWEEN oneMonthBefore AND vDated - ) - WHERE updated = vDated; - - -- Indicadores de producción - UPDATE indicators i - JOIN productionIndicators pi ON pi.dated = i.updated - SET i.productionHours = pi.productionHours, - i.dailyWorkersCost = pi.dailyWorkersCost, - i.volumeM3 = pi.volumeM3, - i.salesValue = pi.salesValue, - i.valueM3 = pi.valueM3, - i.hoursM3 = pi.hoursM3, - i.workerCostM3 = pi.workerCostM3, - i.salesWorkersCostRate = pi.salesWorkersCostRate - WHERE updated BETWEEN oneMonthBefore AND vDated; - - -- CAP Para el calculo de las ventas agrupado por semanas - - SELECT week - FROM vn.time - WHERE dated=vDated INTO vWeek; - - TRUNCATE `bs`.`salesByWeek`; - - INSERT INTO `bs`.`salesByWeek` (week,year,sales) - SELECT `t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales` - FROM `bs`.`ventas` `v` - LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha - GROUP BY `t`.`week` , `t`.`year` - ORDER BY `t`.`week` , `t`.`year`; - - -- CAP Indicador Ventas semana actual - UPDATE indicators i - JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated) - SET i.thisWeekSales = s.sales - WHERE updated = vDated; - - -- CAP indicador ventas semana actual en el año pasado - UPDATE indicators i - JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)-1 - SET i.lastYearWeekSales = s.sales - WHERE updated = vDated; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdateLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdateLauncher`() -BEGIN - - DECLARE vDated DATE; - - SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') - INTO vDated - FROM bs.indicators; - - WHILE vDated < CURDATE() DO - - CALL indicatorsUpdate(vDated); - - SELECT TIMESTAMPADD(DAY,1,MAX(updated)) - INTO vDated - FROM bs.indicators; - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `m3Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `m3Add`() -BEGIN - - DECLARE datSTART DATE; - DECLARE datEND DATE; - - SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART - FROM bs.m3; - - SET datEND = TIMESTAMPADD(DAY,-1,CURDATE()); - - 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(i.compression * s.quantity * r.cm3) / 1000000 AS m3, - tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) - 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 bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas" - JOIN vn.time tm ON tm.dated = v.fecha - JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk - JOIN vn.address a ON a.id = t.addressFk - WHERE v.fecha BETWEEN datSTART AND datEND - AND s.quantity > 0 -- evita abonos - AND t.companyFk = 442 -- Verdnatura - GROUP BY t.warehouseFk, v.fecha, a.provinceFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`() -BEGIN -DECLARE vToDated DATE; - DECLARE vFromDated DATE; - DECLARE vForDeleteDated DATE; - DECLARE vManaId INT DEFAULT 37; - DECLARE vManaAutoId INT DEFAULT 39; - DECLARE vManaBankId INT DEFAULT 66; - DECLARE vManaGreugeTypeId INT DEFAULT 3; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - DELETE - FROM bs.manaCustomer - WHERE dated = vFromDated; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO - - SELECT - timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO - vToDated, - vForDeleteDated; - - DELETE FROM bs.manaCustomer - WHERE dated <= vForDeleteDated; - - - INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated) - - SELECT - Id_Cliente, - cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM - - ( - SELECT cs.Id_Cliente, Cantidad * Valor as mana - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE Id_Componente IN (vManaAutoId, vManaId) - 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 <= vToDated - - UNION ALL - - SELECT g.Id_Cliente, g.Importe - FROM vn2008.Greuges g - WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated - AND Fecha <= vToDated - - UNION ALL - - SELECT Id_Cliente, mana - FROM bs.manaCustomer - WHERE dated = vFromDated - ) sub - - GROUP BY Id_Cliente - HAVING Id_Cliente; - - SET vFromDated = vToDated; - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaSpellers_actualize` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaSpellers_actualize`() -BEGIN - - /* PAK 2019/08/09 updated - * - * Recalcula el valor del campo con el modificador de precio para el componente de maná automático. - * La tabla mana_spellers es una caché - * - */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mermasCacheUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mermasCacheUpdate`() -BEGIN - - DECLARE vTimeRange INT DEFAULT 30; - DECLARE vCurYearStarted DATE DEFAULT TIMESTAMPADD(DAY, - vTimeRange, CURDATE()); - DECLARE vCurYearFinished DATE DEFAULT CURDATE(); - DECLARE vLastYearStarted DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearStarted); - DECLARE vLastYearFinished DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearFinished); - - REPLACE bs.mermasCache - SELECT Comprador, - IF(Fecha < vCurYearStarted, year(CURDATE()) - 1,year(CURDATE())) año, - CAST(sum(Importe) as DECIMAL(10,0)) as Valor_Compra, - CAST(sum(IF(Cliente LIKE 'FALTAS',Importe,0)) as DECIMAL(10,0)) as Faltas, - CAST(sum(IF(Cliente LIKE 'BASURA',Importe,0)) as DECIMAL(10,0)) as Basura - FROM bs.mermas - WHERE Fecha BETWEEN vCurYearStarted AND vCurYearFinished - OR Fecha BETWEEN vLastYearStarted AND vLastYearFinished - GROUP BY año, Comprador; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchAll` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vNErrors INT DEFAULT 0; - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vId INT; - - DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - OPEN rs; - - myLoop: LOOP - SET vDone = FALSE; - FETCH rs INTO vId, vSchema, vProcedure; - - IF vDone THEN - LEAVE myLoop; - END IF; - - UPDATE nightTask - SET `started` = NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vId; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - SET vNErrors = vNErrors + 1; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vId; - ELSE - UPDATE nightTask - SET finished = NOW(), - lastFinished = NOW() - WHERE id = vId; - END IF; - END LOOP; - - CLOSE rs; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - IF vNErrors > 0 AND vLogMail IS NOT NULL THEN - INSERT INTO vn.mail SET - `sender` = vLogMail, - `subject` = 'Nightly task failed', - `body` = CONCAT( - vNErrors, ' procedures of nightly tasks have failed. ', - 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' - ); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchTask` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchTask`( - vSchema VARCHAR(255), - vProcedure VARCHAR(255), - OUT vError VARCHAR(255), - OUT vErrorCode VARCHAR(255) -) -BEGIN -/** - * Runs an specific procedure from nightly tasks, if an error - * occurs, instead of throw it, #vError and #vErrorCode variables - * are setted. - * - * @param vSchema The procedure schema - * @param vProcedure The procedure name - * @param vError The error message, if any - * @param vErrorCode The error code, if any - */ - DECLARE EXIT HANDLER FOR SQLEXCEPTION - GET DIAGNOSTICS CONDITION 1 - vError = MESSAGE_TEXT, - vErrorCode = RETURNED_SQLSTATE; - - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `payMethodClientAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `payMethodClientAdd`() -BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) - SELECT CURDATE(), c.payMethodFk, c.id - 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) - FROM bs.payMethodClient p - 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; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE) -BEGIN - - DECLARE vDateStart DATETIME DEFAULT vDate; - DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - DECLARE myDepLft INT; - DECLARE myDepRgt INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.productivity; - - CREATE TEMPORARY TABLE tmp.productivity - ENGINE = MEMORY - SELECT hh, - mm, - 000.00 as m3, - 000.00 as m3FV, - 000.00 as m3PCA, - 000.00 as m3Artificial, - 0 as workers, - 000.00 as wCost, - 0 as numCoordinadores, - 000.00 as costCoordinacion, - 0 as numSacadores, - 000.00 as costSacado, - 0 as numEncajadores, - 000.00 as costEncajado, - 0 as numPaletizadores, - 000.00 as costPaletizado, - 0 as numCamareros, - 000.00 as costCamara, - 0 as numComplementos, - 000.00 as costComplementos, - 0 as numArtificial, - 000.00 as costArtificial - FROM vn.dayMinute; - --- Trabajadores - CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker - CALL vn.workerDepartmentByDate(vDate); - - -- General - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - WHERE Almacen IN (1,44) - AND wdd.production - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.workers = sub.workers, p.wCost = sub.Bruto; - - -- Coordinadores - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'COORDINACION'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numCoordinadores = sub.workers, p.costCoordinacion = sub.Bruto; - - -- Sacado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'SACADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numSacadores = sub.workers, p.costSacado = sub.Bruto; - - -- Encajado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'ENCAJADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numEncajadores = sub.workers, p.costEncajado = sub.Bruto; - - -- Paletizado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'PALETIZADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numPaletizadores = sub.workers, p.costPaletizado = sub.Bruto; - - -- Cámara - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'CAMARA'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numCamareros = sub.workers, p.costCamara = sub.Bruto; - - -- Complementos - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'COMPLEMENTOS'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numComplementos = sub.workers, p.costComplementos = sub.Bruto; - - -- Artificial - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'ARTIFICIAL'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numArtificial = sub.workers, p.costArtificial = sub.Bruto; - - -- m3 - CALL vn.ticketBuiltTime(vDate); -- Genera la tabla tmp.ticketBuiltTime(ticketFk,builtTime) - CALL vn.ticketVolumeByDate_ventas(vDate); -- Genera la tabla tmp.ticketVolumeByDate(ticketFk,m3), filtrado por las ventas validas - CALL vn.ticketVolumeByDate_ventas_Artificial(vDate); -- Genera la tabla tmp.ticketVolumeByDate_ventas_Artificial - - UPDATE tmp.productivity p - JOIN - (SELECT HOUR(builtTime) hh, - MINUTE(builtTime) mm, - sum(tvd.m3) as m3, - sum(IF(t.warehouseFk = 1,tvd.m3,0)) as m3FV, - sum(IF(t.warehouseFk = 44,tvd.m3 - IFNULL(tvda.m3,0),0)) as m3PCA, - sum(IFNULL(tvda.m3,0)) as m3Artificial - FROM tmp.ticketBuiltTime tbt - JOIN tmp.ticketVolumeByDate tvd ON tvd.ticketFk = tbt.ticketFk - LEFT JOIN tmp.ticketVolumeByDate_Artificial tvda ON tvda.ticketFk = tbt.ticketFk - JOIN vn.ticket t ON t.id = tbt.ticketFk - WHERE t.warehouseFk IN (1,44) - GROUP BY hh,mm - ) v ON v.hh = p.hh AND v.mm = p.mm - SET p.m3 = v.m3, p.m3FV = v.m3FV, p.m3PCA = v.m3PCA, p.m3Artificial = v.m3Artificial; - - - - DELETE FROM bs.productivity - WHERE dated = vDate; - - INSERT INTO bs.productivity(dated, - hh, - mm, - m3, - m3FV, - m3PCA, - m3Artificial, - workers, - wCost, - numCoordinadores, - costCoordinacion, - numSacadores, - costSacado, - numEncajadores, - costEncajado, - numPaletizadores, - costPaletizado, - numCamareros, - costCamara, - numComplementos, - costComplementos, - numArtificial, - costArtificial) - SELECT vDate, - hh, - mm, - m3, - m3FV, - m3PCA, - m3Artificial, - workers, - wCost, - numCoordinadores, - costCoordinacion, - numSacadores, - costSacado, - numEncajadores, - costEncajado, - numPaletizadores, - costPaletizado, - numCamareros, - costCamara, - numComplementos, - costComplementos, - numArtificial, - costArtificial - FROM tmp.productivity p; - - -- Productivity Evolution - REPLACE bs.productivity_evolution(dated, m3productionCost) - SELECT CURDATE(), sum(wCost) / sum(m3) - FROM bs.productivity - WHERE dated BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE(); - - DROP TEMPORARY TABLE tmp.dayMinuteWorker; - DROP TEMPORARY TABLE tmp.productivity; - DROP TEMPORARY TABLE tmp.ticketBuiltTime; - DROP TEMPORARY TABLE tmp.ticketVolumeByDate; - DROP TEMPORARY TABLE tmp.workerDepartmentByDate; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) -BEGIN - - DECLARE vEndingDate DATETIME; - - SET vEndingDate = vDateStart; - - WHILE vEndingDate <= vDateEndPeriod DO - REPLACE INTO bs.productivityDepartment - SELECT vEndingDate, - CAST(((productivityCoordinacionLastYear - productivityCoordinacion) / 2) * m3 AS DECIMAL (10,2)) AS amountCoordinacion, - CAST(((productivitySacadoLastYear - productivitySacado) / 2) * m3 AS DECIMAL (10,2)) AS amountSacado, - CAST(((productivityEncajadoLastYear - productivityEncajado) / 2) * m3 AS DECIMAL (10,2)) AS amountEncajado, - CAST(((productivityPaletizadoLastYear - productivityPaletizado) / 2) * m3 AS DECIMAL (10,2)) AS amountPaletizado, - CAST(((productivityCamaraLastYear - productivityCamara) / 2) * m3FV AS DECIMAL (10,2)) AS amountCamara, - CAST(((productivityComplementosLastYear - productivityComplementos) / 2) * m3PCA AS DECIMAL (10,2)) AS amountComplementos, - CAST(((productivityArtificialLastYear - productivityArtificial) / 2) * m3Artificial AS DECIMAL (10,2)) AS amountArtificia - FROM - (SELECT - SUM(p.m3) AS m3, SUM(p.m3FV) as m3FV, SUM(p.m3PCA) as m3PCA, SUM(p.m3Artificial) as m3Artificial, - SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacion, - SUM(p.costSacado) / SUM(p.m3) AS productivitySacado, - SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajado, - SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizado, - SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamara, - SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementos, - SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificial - FROM - bs.productivity p - WHERE - p.dated BETWEEN vDateStartPeriod AND vEndingDate) sub - JOIN - (SELECT - SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacionLastYear, - SUM(p.costSacado) / SUM(p.m3) AS productivitySacadoLastYear, - SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajadoLastYear, - SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizadoLastYear, - SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamaraLastYear, - SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementosLastYear, - SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificialLastYear - FROM - bs.productivity p - WHERE - p.dated BETWEEN DATE_ADD(vDateStartPeriod, INTERVAL - 1 YEAR) AND DATE_ADD(vEndingDate, INTERVAL - 1 YEAR)) sub1; - - SET vEndingDate = TIMESTAMPADD(DAY,1, vEndingDate); - END WHILE; - END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`() -BEGIN - CALL bs.productivityDepartmentAdd('2019-05-06', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`() -BEGIN - - DECLARE vDateFrom DATE; - - SELECT LEAST(TIMESTAMPADD(MONTH, -1, CURDATE()),MAX(dated)) - INTO vDateFrom - FROM bs.productivity; - - WHILE CURDATE() > vDateFrom DO - CALL bs.productivityAdd(vDateFrom); - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - END WHILE; - - SET vDateFrom = TIMESTAMPADD(MONTH, -13, CURDATE()); - - WHILE TIMESTAMPADD(MONTH, -12, CURDATE()) > vDateFrom DO - CALL bs.productivityAdd(vDateFrom); - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher_manual` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual`(vDateFrom DATE, vToDate DATE) -BEGIN - - TRUNCATE tmp.log; - - WHILE vToDate >= vDateFrom DO - - INSERT INTO tmp.log(text) VALUES (vDateFrom); - CALL bs.productivityAdd(vDateFrom); - - CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); - INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); - - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `pruebas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `pruebas`(IN vDateStart DATE, IN vDateEnd DATE) -BEGIN - -WHILE vDateStart <> vDateEnd -DO - UPDATE indicators - SET countEmployee = - ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) - FROM - postgresql.business AS b - JOIN postgresql.profile p ON p.profile_id = b.provider_id - JOIN postgresql.person pe ON pe.person_id = p.person_id - LEFT JOIN - postgresql.business_labour AS bl ON bl.business_id = b.business_id - LEFT JOIN - postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - WHERE - (vDateStart BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDateStart)) - AND pe.name = 'VERDNATURA LEVANTE SL' - ) - WHERE updated = vDateStart; - SET vDateStart = DATE_ADD(vDateStart, INTERVAL 1 DAY); - -END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) -BEGIN - DELETE FROM bs.salePersonEvolution - WHERE dated <= DATE_SUB(CURDATE(), INTERVAL 1 YEAR); - - - INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - 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.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; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userSundayRole` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole`() -BEGIN - -- 4996 Fran Natek Echevarria - DECLARE vDay INT; - SET vDay := (SELECT DAYOFWEEK(CURDATE())); - IF vDay = 1 THEN - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesAssistant"; - ELSE - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesPerson"; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(intYEAR INT, vQuarter INT) -BEGIN - - DECLARE comisionRate DOUBLE DEFAULT 0.029; - - REPLACE vendedores - SELECT c.Id_Trabajador - , intYEAR - , MONTH(v.fecha) intMONTH - , sum(importe) as importe - , sum(importe) * 0.029 as comision - , 0 as comisionCedida - , 0 as comisionArrendada - , 0 as comisionNuevos - - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month`; - - -- Ventas nuevas - UPDATE vendedores v - JOIN - ( - SELECT c.Id_Trabajador - , sum(importe) * 0.029 as comisionNueva - , t.`month` - , t.`year` - FROM ventas v - JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionNuevos = sub.comisionNueva, v.comision = v.comision - sub.comisionNueva; - - -- Ventas cedidas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_old as Id_Trabajador - , sum(importe) * 0.029 * comision_old as cedido - , sum(importe) * 0.029 * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_old, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionCedida = sub.cedido, v.comision = v.comision - sub.cedido - sub.arrendada; - - -- Ventas arrendadas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_new as Id_Trabajador - , sum(importe) * 0.029 * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_new, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionArrendada = sub.arrendada; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() -BEGIN - - call bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); - - call bs.vendedores_evolution_add; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_evolution_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes - -*/ - -DECLARE vYear, vMonth INTEGER; -DECLARE vCurYear, vCurMonth INTEGER; -DECLARE vFirstYear INTEGER DEFAULT 2017; -DECLARE vFirstMonth INTEGER DEFAULT 1; - -DECLARE vDateFrom DATE; -DECLARE vDateTo DATE; - -SET vCurYear = year(CURDATE()); -SET vCurMonth = month(CURDATE()); - -SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) - INTO vYear, vMonth - 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; - - SELECT vDateTo, vDateFrom, vYear, vMonth; - - REPLACE bs.vendedores_evolution( workerFk - , year - , month - , sales) - SELECT c.salesPersonFk - , vYear as year - , vMonth as month - , sum(v.importe) as sales - 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; - - END IF; - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - IF datSTART < '2015-10-01' OR datEND < '2015-10-01' THEN - CALL util.throw('fechaDemasiadoAntigua'); - END IF; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = datSTART; - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() -BEGIN - - call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add__`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = GREATEST('2015-10-01',datSTART); - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND datEND >= '2015-10-01' - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND c.Id_Trabajador IS NOT NULL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) -BEGIN -/** - * Reemplaza las ventas contables. 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)) - 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; - - -DROP TEMPORARY TABLE tmp.ticket_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() -BEGIN - - call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_por_cliente` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) -BEGIN - - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - 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; - - - - SELECT vYear Año - , vMonth Mes - , t.Id_Cliente - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , t.empresa_id empresa - 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 != 188 - GROUP BY t.Id_Cliente, grupo,t.empresa_id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vivosMuertos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() -BEGIN - -SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); -SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),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 -JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm -LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - 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 - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth 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 - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Muerto = 1 -WHERE yearMonth < @lastYearMonth; - - SELECT * FROM tmp.VivosMuertos; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed`() -BEGIN - - /* #UPDATED PAK 2019/09/02 - * #PENDING REVIEW - * - * - * - * - */ - - DECLARE vLastUpdated DATETIME; - DECLARE vSecondsDelay INT DEFAULT 300; - - SELECT IFNULL(MAX(lastUpdated),CURDATE()) INTO vLastUpdated - FROM bs.workerSpeed; - - IF TIMESTAMPDIFF(SECOND, vLastUpdated, NOW()) > vSecondsDelay THEN - - DELETE FROM bs.workerSpeed ; - -- WHERE lastUpdated < CURDATE(); - - -- Sacadores - REPLACE bs.workerSpeed - SELECT workerCode, - accion, - warehouseFk, - CAST(60 * sumaLitros / time_to_sec(timediff(finished, started)) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sumaLitrosLastHour / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM - ( - SELECT warehouseFk, - accion, - workerCode, - sum(litros) as sumaLitros, - min(created) as started, - max(created) as finished, - sum(IF(created >= TIMESTAMPADD(HOUR, -1, NOW()),litros, 0)) as sumaLitrosLastHour - FROM - ( - SELECT t.warehouseFk, - st.saleFk, - st.isChecked, - st.originalQuantity, - a.accion, - st.created, - e.code, - w.firstname, - w.lastName, - w.code as workerCode, - r.cm3 * s.quantity / 1000 as litros, - s.concept - FROM vn.saleTracking st - LEFT JOIN - (SELECT saleFk - FROM vn.saleTracking st - JOIN vn.state e ON e.id = st.stateFk - WHERE st.created > CURDATE() - AND e.code LIKE 'PREVIOUS_PREPARATION') prevPrepSales ON prevPrepSales.saleFk = st.saleFk - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > TIMESTAMPADD(HOUR,-1,NOW()) - AND prevPrepSales.saleFk IS NULL - ) sub - GROUP BY warehouseFk, accion, workerCode - ) sub2; - - -- Encajadores - REPLACE bs.workerSpeed - SELECT code as workerCode, - 'ENCAJAR' as accion, - warehouseFk, - CAST(60 * sum(Litros) / time_to_sec(timediff(MAX(finished), MIN(started))) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sum(litrosUltimaHora) / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM ( - SELECT sv.ticketFk, - sum(sv.litros) as litros, - sum(IF(started > TIMESTAMPADD(HOUR,-1,NOW()),sv.litros,0)) as litrosUltimaHora, - code, - started, - finished, - cajas, - warehouseFk - FROM vn.saleVolume sv - JOIN - ( - SELECT ticketFk, - min(e.created) as started, - max(e.created) as finished, - max(counter) as cajas, - w.code, - t.warehouseFk - FROM vn.expedition e - JOIN vn.worker w ON w.id = e.workerFk - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE e.created > CURDATE() - GROUP BY ticketFk - ) sub ON sub.ticketFk = sv.ticketFk - GROUP BY sv.ticketFk) sub2 - GROUP BY code; - - END IF; - - SELECT * FROM bs.workerSpeed; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed_detail` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed_detail`(vWorkerCode VARCHAR(3), vAction VARCHAR(25)) -BEGIN - - SELECT * FROM - ( - SELECT time_format(st.created,'%H:%i') as hora, - t.warehouseFk as Almacen, - t.id as ticketFk, - floor(sum(s.quantity * r.cm3) / 1000) as Litros - - FROM vn.saleTracking st - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > CURDATE() - AND a.accion LIKE vAction - AND w.code LIKE vWorkerCode - GROUP BY t.id) sub - ORDER BY hora; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - -- -- Current Database: `cache` -- @@ -14242,9 +10792,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -14288,9 +10838,9 @@ BEGIN GROUP BY r.warehouse_id; DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate FROM order_row r - JOIN vn2008.Articles a ON a.Id_Article = r.item_id + JOIN vn.item i ON i.id = r.item_id WHERE r.amount != 0 AND r.warehouse_id = vWarehouse AND r.order_id = vOrder @@ -14308,12 +10858,12 @@ BEGIN -- Carga los datos del pedido SELECT o.date_send, o.address_id, o.note, - o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id + o.confirmed, a.clientFk, o.company_id, o.agency_id INTO vDelivery, vAddress, vNotes, vIsConfirmed, vClientId, vCompanyId, vAgencyModeId FROM hedera.`order` o - JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id - WHERE id = vOrder; + JOIN vn.address a ON a.id = o.address_id + WHERE o.id = vOrder; -- Comprueba que el pedido no está confirmado @@ -14332,7 +10882,7 @@ BEGIN -- Carga las fechas de salida de cada almacén - CALL vn.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); -- Trabajador que realiza la acción @@ -14358,19 +10908,18 @@ BEGIN -- Busca un ticket existente que coincida con los parametros - SELECT Id_Ticket INTO vTicket - FROM vn2008.Tickets t - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN vn.ticketState tls on tls.ticket = t.id JOIN `order` o - ON o.address_id = t.Id_Consigna - AND vWarehouse = t.warehouse_id - AND o.agency_id = t.Id_Agencia - AND t.landing = o.date_send - AND vShipment = DATE(t.Fecha) + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.agency_id = t.agencyModeFk + AND o.date_send = t.landed + AND vShipment = DATE(t.shipped) WHERE o.id = vOrder - AND t.Factura IS NULL + AND t.invoiceOutFk IS NULL AND IFNULL(tls.alertLevel,0) = 0 - AND t.Id_Cliente <> 1118 LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado @@ -14392,23 +10941,24 @@ BEGIN ELSE INSERT INTO vncontrol.inter SET Id_Ticket = vTicket, + Id_Trabajador = vUserId, state_id = TICKET_FREE; END IF; - INSERT IGNORE INTO vn2008.order_Tickets - SET order_id = vOrder, - Id_Ticket = vTicket; + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vOrder, + ticketFk = vTicket; -- Añade las notas IF vNotes IS NOT NULL AND vNotes != '' THEN - INSERT INTO vn2008.ticket_observation SET - Id_Ticket = vTicket, - observation_type_id = 4 /* salesperson */ , - `text` = vNotes + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */ , + `description` = vNotes ON DUPLICATE KEY UPDATE - `text` = CONCAT(VALUES(`text`),'. ', `text`); + `description` = CONCAT(VALUES(`description`),'. ', `description`); END IF; -- Añade los movimientos y sus componentes @@ -14424,20 +10974,20 @@ BEGIN LEAVE lRows; END IF; - INSERT INTO vn2008.Movimientos + INSERT INTO vn.sale SET - Id_Article = vItem, - Id_Ticket = vTicket, - Concepte = vConcept, - Cantidad = vAmount, - Preu = vPrice, - CostFixat = 0, - PrecioFijado = TRUE; + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; SET vSale = LAST_INSERT_ID(); - INSERT INTO vn2008.Movimientos_componentes - (Id_Movimiento, Id_Componente, Valor) + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) SELECT vSale, cm.component_id, cm.price FROM order_component cm JOIN bi.tarifa_componentes tc @@ -14458,20 +11008,20 @@ BEGIN CREATE TEMPORARY TABLE tComponents (INDEX (saleFk)) ENGINE = MEMORY - SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc USING(Id_Componente) + SELECT SUM(sc.`value`) valueSum, sc.saleFk + FROM vn.saleComponent sc + JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk JOIN bi.tarifa_componentes_series tcs ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base - JOIN vn2008.Movimientos m - ON m.Id_Movimiento = mc.Id_Movimiento - WHERE m.Id_Ticket = vTicket - GROUP BY mc.Id_Movimiento; + JOIN vn.sale s + ON s.id = sc.saleFk + WHERE s.ticketFk = vTicket + GROUP BY sc.saleFk; - UPDATE vn2008.Movimientos m - JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento - SET m.CostFixat = valueSum; + UPDATE vn.sale s + JOIN tComponents mc ON mc.saleFk = s.id + SET s.priceFixed = valueSum; DROP TEMPORARY TABLE tComponents; END LOOP; @@ -15148,9 +11698,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -15218,7 +11768,7 @@ BEGIN ,vEmployee ,vDate FROM tpvMerchant m - JOIN tpvConfig c ON c.id = 1 + JOIN tpvConfig c LEFT JOIN tpvTransaction t ON t.id = vOrder WHERE m.id = vMerchant; @@ -15238,7 +11788,7 @@ BEGIN -- Código redundante - DO vn2008.till_entry + DO vn.till_new ( vCustomer ,vBank @@ -15265,7 +11815,6 @@ BEGIN ,errorCode = vErrorCode ,status = vStatus WHERE id = vOrder; - COMMIT; END ;; DELIMITER ; @@ -15370,9 +11919,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -15414,33 +11963,33 @@ BEGIN -- Elimina el recibo - DELETE FROM vn2008.Recibos - WHERE Id = vReceipt LIMIT 1; + DELETE FROM vn.receipt + WHERE id = vReceipt LIMIT 1; -- Elimina la entrada de cajas - DELETE FROM vn2008.Cajas - WHERE Id_Banco = vBank - AND DATE(CajaFecha) = vDate - AND Entrada = vAmount + DELETE FROM vn.till + WHERE bankFk = vBank + AND DATE(dated) = vDate + AND `in` = vAmount LIMIT 1; -- Elimina los asientos contables - SELECT Cuenta INTO vSubaccount - FROM vn2008.Clientes WHERE Id_Cliente = vCustomer; + SELECT accountingAccount INTO vSubaccount + FROM vn.`client` WHERE id = vCustomer; - SELECT Cuenta INTO vAccount - FROM vn2008.Bancos WHERE Id_Banco = vBank; + SELECT account INTO vAccount + FROM vn.bank WHERE id = vBank; - DELETE FROM vn2008.XDiario + DELETE FROM vn.XDiario WHERE SUBCTA = vSubaccount AND CONTRA = vAccount AND DATE(FECHA) = vDate AND EUROHABER = vAmount LIMIT 1; - DELETE FROM vn2008.XDiario + DELETE FROM vn.XDiario WHERE CONTRA = vSubaccount AND SUBCTA = vAccount AND DATE(FECHA) = vDate @@ -17897,7 +14446,7 @@ CREATE TABLE `log` ( `tableId` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `tableName` (`tableName`,`tableId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -18292,16 +14841,57 @@ DELIMITER ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) +proc: BEGIN + -- XXX: Disabled while testing + LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_add_beta` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) proc: BEGIN -- XXX: Disabled while testing - LEAVE proc; - - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + DECLARE vLanded DATE; + DECLARE vWarehouseFk INT; + DECLARE vBuyerFk INT; + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vItemName VARCHAR(50); + + -- LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN INSERT IGNORE INTO `log` SET tableName = vTableName, tableId = vOldId, @@ -18313,7 +14903,36 @@ proc: BEGIN tableName = vTableName, tableId = vNewId, operation = 'insert'; - END IF; + END IF; + + IF vTableName = 'buy' THEN + + SELECT IFNULL(tr.landed,'2000-01-01') + INTO vLanded + FROM vn.travel tr + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + JOIN vn.warehouse w ON w.id = tr.warehouseInFk + WHERE b.id = vNewId + AND w.isBuyerToBeEmailed; + + IF vLanded = CURDATE() THEN + + SELECT it.workerFk, b.entryFk, i.id, i.longName + INTO vBuyerFk, vEntryFk, vItemFk, vItemName + FROM vn.itemType it + JOIN vn.item i ON i.typeFk = it.id + JOIN vn.buy b ON b.itemFk = i.id + WHERE b.id = vNewId; + + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E-',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName), + 'Este email se ha generado automáticamente'); + + END IF; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20955,6 +17574,22 @@ CREATE TABLE `chain` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `chatConfig` +-- + +DROP TABLE IF EXISTS `chatConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `chatConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `uri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `password` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `claim` -- @@ -21373,9 +18008,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -21383,9 +18018,7 @@ DELIMITER ;; BEFORE UPDATE ON `client` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE DECLARE vText VARCHAR(255) DEFAULT NULL; - -- Comprueba que el formato de los teléfonos es válido IF !(NEW.phone <=> OLD.phone) THEN @@ -21395,7 +18028,7 @@ BEGIN IF !(NEW.mobile <=> OLD.mobile) THEN CALL pbx.phone_isValid(NEW.mobile); END IF; - + IF !(NEW.fax <=> OLD.fax) THEN CALL pbx.phone_isValid(NEW.fax); END IF; @@ -21416,7 +18049,7 @@ BEGIN IF vText IS NOT NULL THEN - INSERT INTO vn2008.mail(`to`, reply_to, subject, text) + INSERT INTO mail(sender, replyTo, `subject`, body) SELECT CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), 'administracion@verdnatura.es', @@ -21577,14 +18210,31 @@ CREATE TABLE `clientLog` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Temporary table structure for view `clientManaCache` +-- Table structure for table `clientManaCache` -- DROP TABLE IF EXISTS `clientManaCache`; -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientManaCache` ( + `clientFk` int(11) NOT NULL, + `mana` decimal(10,0) NOT NULL DEFAULT '0', + `dated` date NOT NULL, + PRIMARY KEY (`clientFk`,`dated`), + KEY `manaCustomerIdx1` (`dated`), + CONSTRAINT `cliente_fk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `clientManaCache__` +-- + +DROP TABLE IF EXISTS `clientManaCache__`; +/*!50001 DROP VIEW IF EXISTS `clientManaCache__`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientManaCache` AS SELECT +/*!50001 CREATE VIEW `clientManaCache__` AS SELECT 1 AS `clientFk`, 1 AS `mana`, 1 AS `dated`*/; @@ -21862,6 +18512,22 @@ SET character_set_client = utf8; 1 AS `level`*/; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `collectionVolumetry` +-- + +DROP TABLE IF EXISTS `collectionVolumetry`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collectionVolumetry` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `level` int(10) unsigned NOT NULL DEFAULT '0', + `lines` int(10) unsigned NOT NULL DEFAULT '1', + `liters` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `company` -- @@ -21931,7 +18597,8 @@ SET character_set_client = utf8; 1 AS `typeFk`, 1 AS `classRate`, 1 AS `tax`, - 1 AS `isRenewable`*/; + 1 AS `isRenewable`, + 1 AS `code`*/; SET character_set_client = @saved_cs_client; -- @@ -22334,21 +19001,20 @@ CREATE TABLE `creditClassification` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE IF NEW.client <> OLD.client THEN CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); END IF; IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE vn2008.Clientes c - SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client; + UPDATE `client` c + SET creditInsurance = 0 WHERE c.id = NEW.client; END IF; END */;; DELIMITER ; @@ -22378,17 +19044,16 @@ CREATE TABLE `creditInsurance` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE - UPDATE vn2008.Clientes c - JOIN vn.creditClassification cc ON cc.client = c.Id_Cliente + UPDATE `client` c + JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; END */;; @@ -22737,13 +19402,18 @@ CREATE TABLE `dms` ( `contentType` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `hasFile` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) NOT NULL, + `workerFk` int(11) DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`), KEY `trabajador_id` (`workerFk`), - KEY `warehouse_id` (`warehouseFk`) + KEY `warehouse_id` (`warehouseFk`), + KEY `dms_dmsTypeFk_idx` (`dmsTypeFk`), + CONSTRAINT `dms_companyFk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_dmsTypeFk` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='document managment system'; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -23117,24 +19787,23 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeUpdate` +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`entry_beforeUpdate` BEFORE UPDATE ON `entry` FOR EACH ROW BEGIN - -- Bernat: working in this file - DECLARE vIsClone BOOL; + DECLARE vIsVirtual BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; IF !(NEW.travelFk <=> OLD.travelFk) THEN - SELECT COUNT(*) > 0 INTO vIsClone - FROM vn2008.Entradas_Auto WHERE Id_Entrada = NEW.id; + SELECT COUNT(*) > 0 INTO vIsVirtual + FROM entryVirtual WHERE entryFk = NEW.id; SELECT !(o.warehouseInFk <=> n.warehouseInFk) OR !(o.warehouseOutFk <=> n.warehouseOutFk) @@ -23143,7 +19812,7 @@ BEGIN WHERE o.id = OLD.travelFk AND n.id = NEW.travelFk; - IF vIsClone AND vHasDistinctWarehouses THEN + IF vIsVirtual AND vHasDistinctWarehouses THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; END IF; @@ -23171,12 +19840,11 @@ BEGIN END IF; IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN - INSERT INTO vn2008.Entradas_dits SET - idaccion_dits = 105, - Id_Trabajador = myWorker_getId(), - Id_Ticket = NEW.id, - value_old = OLD.isBooked, - value_new = NEW.isBooked; + INSERT INTO entryLog SET + action = 'update', + description = 'Cambia a Contabilizada', + userFk = myWorker_getId(), + originFk = NEW.id; END IF; END */;; DELIMITER ; @@ -23476,7 +20144,6 @@ CREATE TABLE `expedition` ( DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`expedition_beforeInsert` BEFORE INSERT ON `expedition` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one BEGIN DECLARE intcounter INT; DECLARE vShipFk INT; @@ -23497,11 +20164,10 @@ BEGIN SET NEW.`counter` = intcounter; END IF; - -- JGF 14/01/19 si existe un polizon queda anulado SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; IF vShipFk THEN - CALL stowawayUnBoarding(vShipFk, NEW.ticketFk); + CALL stowaway_unboarding(vShipFk, NEW.ticketFk); END IF; END */;; DELIMITER ; @@ -25902,6 +22568,20 @@ CREATE TABLE `packaging` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `packagingConfig` +-- + +DROP TABLE IF EXISTS `packagingConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `packagingConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `upperGap` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `parking` -- @@ -25986,6 +22666,7 @@ DROP TABLE IF EXISTS `payMethod`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `payMethod` ( `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(50) CHARACTER SET utf8 DEFAULT NULL, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `solution` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, `outstandingDebt` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000', @@ -26422,6 +23103,36 @@ CREATE TABLE `printServerQueue` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `printServerQueue2` +-- + +DROP TABLE IF EXISTS `printServerQueue2`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `printServerQueue2` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `printerFk` tinyint(3) unsigned DEFAULT NULL, + `priorityFk` tinyint(3) unsigned DEFAULT NULL, + `reportFk` tinyint(3) unsigned DEFAULT '0', + `statusFk` tinyint(3) unsigned DEFAULT '1', + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, + `param1` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `workerFk` int(11) DEFAULT '20', + `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `param3` text COLLATE utf8_unicode_ci, + `error` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`), + KEY `Id_estado` (`statusFk`), + KEY `Id_Impresora` (`printerFk`), + KEY `Id_Informe` (`reportFk`), + KEY `Id_Prioridad` (`priorityFk`), + KEY `Id_Trabajador` (`workerFk`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `printingQueueCheck` -- @@ -26848,11 +23559,14 @@ CREATE TABLE `route` ( `cost` double unsigned DEFAULT NULL, `m3` decimal(10,1) unsigned DEFAULT NULL, `description` text COLLATE utf8_unicode_ci, + `zoneFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Id_Agencia` (`agencyModeFk`), KEY `Fecha` (`created`), KEY `gestdoc_id` (`gestdocFk`), KEY `route_ibfk_2_idx` (`workerFk`), + KEY `fk_route_1_idx` (`zoneFk`), + CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE, CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -27412,6 +24126,7 @@ CREATE TABLE `sector` ( `code` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `pickingPlacement` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `path` int(11) DEFAULT NULL, + `isPreviousPrepared` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -27768,6 +24483,7 @@ CREATE TABLE `state` ( `nextStateFk` tinyint(4) NOT NULL COMMENT 'Estado al que tiene que cambiar el ticket despues de preparacion previa', `isPreviousPreparable` tinyint(1) NOT NULL DEFAULT '0', `isPicked` tinyint(1) NOT NULL DEFAULT '0', + `isPreparable` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -28674,7 +25390,7 @@ CREATE TABLE `ticketRequest` ( `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `isOk` tinyint(1) DEFAULT NULL, `requesterFk` int(11) DEFAULT NULL, - `atenderFk` int(11) DEFAULT NULL, + `attenderFk` int(11) DEFAULT NULL, `ticketFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Id_Movimiento_UNIQUE` (`saleFk`), @@ -28684,10 +25400,10 @@ CREATE TABLE `ticketRequest` ( KEY `Id_Movimiento` (`saleFk`), KEY `Id_Vendedor` (`salesPersonCode`), KEY `fgnRequester_idx` (`requesterFk`), - KEY `fgnAtender_idx` (`atenderFk`), + KEY `fgnAtender_idx` (`attenderFk`), KEY `fgnTicket_idx` (`ticketFk`), CONSTRAINT `fgbMovimiento` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `fgnAtender` FOREIGN KEY (`atenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `fgnAtender` FOREIGN KEY (`attenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -28695,25 +25411,25 @@ CREATE TABLE `ticketRequest` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW BEGIN - IF NEW.ticketFk IS NULL THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.requesterFk IS NULL THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; + IF NEW.ticketFk IS NULL THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; - IF NEW.atenderFk IS NULL THEN - SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; + IF NEW.requesterFk IS NULL THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.attenderFk IS NULL THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28723,25 +25439,25 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW BEGIN - IF NEW.saleFk <> OLD.saleFk THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.salesPersonCode <> OLD.salesPersonCode THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; + IF NEW.saleFk <> OLD.saleFk THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; - IF NEW.buyerCode <> OLD.buyerCode THEN - SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; + IF NEW.salesPersonCode <> OLD.salesPersonCode THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.buyerCode <> OLD.buyerCode THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29248,6 +25964,33 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `travelLog` +-- + +DROP TABLE IF EXISTS `travelLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `travelLog` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `travelObservation` -- @@ -29340,6 +26083,67 @@ CREATE TABLE `userConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuración de usuario en Salix'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `userLog` +-- + +DROP TABLE IF EXISTS `userLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPhone` +-- + +DROP TABLE IF EXISTS `userPhone`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userPhone` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) unsigned NOT NULL, + `typeFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `phone` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UserFk_Phone` (`userFk`,`typeFk`,`phone`), + KEY `fgnTypeFk` (`typeFk`), + CONSTRAINT `fgnTypeFk` FOREIGN KEY (`typeFk`) REFERENCES `userPhoneType` (`code`) ON UPDATE CASCADE, + CONSTRAINT `fgnUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPhoneType` +-- + +DROP TABLE IF EXISTS `userPhoneType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userPhoneType` ( + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `vehicle` -- @@ -29394,6 +26198,7 @@ CREATE TABLE `warehouse` ( `hasStowaway` tinyint(1) NOT NULL DEFAULT '0', `hasDms` tinyint(1) NOT NULL DEFAULT '0', `pickUpAgencyModeFk` int(11) DEFAULT NULL, + `isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `Id_Paises` (`countryFk`), @@ -29811,6 +26616,20 @@ CREATE TABLE `workerMana` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `workerManaExcluded` +-- + +DROP TABLE IF EXISTS `workerManaExcluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `workerManaExcluded` ( + `workerFk` int(11) NOT NULL, + PRIMARY KEY (`workerFk`), + CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `workerMana__` -- @@ -30236,7 +27055,7 @@ CREATE TABLE `zone` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `hour` datetime NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, + `warehouseFk__` smallint(6) unsigned DEFAULT NULL, `agencyModeFk` int(11) NOT NULL, `travelingDays` int(11) NOT NULL DEFAULT '1', `price` double NOT NULL DEFAULT '0', @@ -30244,10 +27063,10 @@ CREATE TABLE `zone` ( `isVolumetric` tinyint(1) NOT NULL DEFAULT '0', `inflation` decimal(5,2) NOT NULL DEFAULT '1.00', PRIMARY KEY (`id`), - KEY `fk_zone_1_idx` (`warehouseFk`), + KEY `fk_zone_1_idx` (`warehouseFk__`), KEY `fk_zone_2_idx` (`agencyModeFk`), KEY `zone_name_idx` (`name`), - CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -30269,6 +27088,49 @@ CREATE TABLE `zoneCalendar` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `zoneEvent` +-- + +DROP TABLE IF EXISTS `zoneEvent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneEvent` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `type` enum('day','indefinitely','range') NOT NULL, + `dated` date DEFAULT NULL, + `started` date DEFAULT NULL, + `ended` date DEFAULT NULL, + `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, + `hour` datetime DEFAULT NULL, + `travelingDays` int(11) DEFAULT NULL, + `price` decimal(10,2) DEFAULT NULL, + `bonus` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `zoneExclusion` +-- + +DROP TABLE IF EXISTS `zoneExclusion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneExclusion` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `dated` date NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk_2` (`zoneFk`,`dated`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `zoneGeo` -- @@ -30366,11 +27228,47 @@ CREATE TABLE `zoneIncluded` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `zoneWarehouse` +-- + +DROP TABLE IF EXISTS `zoneWarehouse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneWarehouse` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), + KEY `warehouseFk` (`warehouseFk`), + CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Dumping events for database 'vn' -- /*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */; +/*!50106 DROP EVENT IF EXISTS `department_doCalc` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8 */ ;; +/*!50003 SET character_set_results = utf8 */ ;; +/*!50003 SET collation_connection = utf8_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; /*!50003 SET @saved_cs_results = @@character_set_results */ ;; @@ -30634,6 +27532,42 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `address_getGeo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `address_getGeo`(vSelf INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed address. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode + WHERE a.id = vSelf + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + RETURN vGeoFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `barcodeToItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -30678,6 +27612,107 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `bionicCalcReverse`(vWarehouse INT, + vMargin DECIMAL(10,3), + vRetailedPrice DECIMAL(10,3), + vM3 DECIMAL(10,3), + vAddress INT, + vAgencyMode INT) RETURNS decimal(10,3) + DETERMINISTIC +BEGIN + DECLARE vGeneralInflationCoeficient INT; + DECLARE vVerdnaturaVolumeBox BIGINT; + DECLARE vClientFk INT; + DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; + DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; + DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; + DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; + DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; + DECLARE vComponentCostValue DECIMAL(10,2); + DECLARE vItem INT DEFAULT 98; + DECLARE vItemCarryBox INT; + + SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox + INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox + FROM bionicConfig; + + SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; + + -- Creamos la tabla tmp.bionicComponent + DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; + CREATE TEMPORARY TABLE tmp.bionicComponent( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `componentFk` int(10) unsigned NOT NULL, + `value` decimal(10,4) NOT NULL, + UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, + KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE + ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + + -- Margin + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id, vMargin + FROM component + WHERE code = vComponentMargin; + + -- Recobro + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) + FROM bi.claims_ratio cr + JOIN component c ON c.code = vComponentRecovery + WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; + + -- Componente de maná automático, en función del maná acumulado por el comercial. + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) + FROM client c + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + JOIN component co ON co.code = vComponentMana + WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; + + -- Reparto + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient + * ROUND( + vM3 + * az.price + * az.inflation + / vVerdnaturaVolumeBox, 4 + ) + FROM agencyMode ag + JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode + JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk + AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk + JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode + AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse + JOIN component co ON co.code = vComponentPort; + + -- Coste + SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue + FROM tmp.bionicComponent; + + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id,vComponentCostValue + FROM component + WHERE code = vComponentCost; + + RETURN vComponentCostValue; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -31112,27 +28147,34 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` FUNCTION `clientGetMana`(vClient INT) RETURNS decimal(10,2) - READS SQL DATA + DETERMINISTIC BEGIN /** - * BERNAT: WORKING IN THIS FILE - * Devuelve el maná del cliente. - * + * Devuelve el mana del cliente. + * * @param vClient Id del cliente - * @return Maná del cliente + * @return Mana del cliente */ - DECLARE vMana DECIMAL(10,2); DECLARE vFromDated DATE; DECLARE vHasMana BOOLEAN; - + DECLARE vManaComponent INT; + DECLARE vAutoManaComponent INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; + SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; + SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; + SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; + SELECT COUNT(*) INTO vHasMana FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; @@ -31142,52 +28184,43 @@ BEGIN END IF; SELECT max(dated) INTO vFromDated - FROM vn.clientManaCache; + FROM clientManaCache; SELECT sum(mana) INTO vMana FROM ( SELECT mana - FROM vn.clientManaCache + FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated - + AND dated = vFromDated UNION ALL - - SELECT s.quantity * Valor - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.sale s on s.ticketFk = t.id - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id - WHERE Id_Componente IN (37, 39) + SELECT s.quantity * value + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN sale s on s.ticketFk = t.id + JOIN saleComponent sc on sc.saleFk = s.id + WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) AND t.shipped > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) AND a.clientFk = vClient - UNION ALL - - SELECT - Entregado - FROM vn2008.Recibos r - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE r.Id_Banco = 66 - AND r.Fechacobro > vFromDated - AND r.Fechacobro <= CURDATE() - AND c.Id_Cliente = vClient - + SELECT - amountPaid + FROM receipt r + JOIN `client` c ON c.id = r.clientFk + WHERE r.bankFk = vManaBank + AND r.payed > vFromDated + AND r.payed <= CURDATE() + AND c.id = vClient UNION ALL - - SELECT g.Importe - FROM vn2008.Greuges g - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE g.Greuges_type_id = 3 -- Maná - AND g.Fecha > vFromDated - AND g.Fecha <= CURDATE() - AND c.Id_Cliente = vClient - + SELECT g.amount + FROM greuge g + JOIN `client` c ON c.id = g.clientFk + WHERE g.greugeTypeFk = vManaGreugeType + AND g.shipped > vFromDated + AND g.shipped <= CURDATE() + AND c.id = vClient ) sub; - RETURN IFNULL(vMana,0); - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31590,9 +28623,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -31606,26 +28639,50 @@ BEGIN DECLARE vCommission INT; DECLARE vCurrentCommission INT; DECLARE vIsCurrencyUsd INT; + DECLARE vLastEntryFk INT; SELECT count(*) INTO vIsCurrencyUsd FROM currency c WHERE c.code = 'USD' AND id = vCurrencyFk; IF NOT vIsCurrencyUsd THEN - SELECT commission INTO vCurrentCommission - FROM supplier s - WHERE s.id = vSupplierFk; - RETURN vCurrentCommission; - END IF; - - SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission - FROM travel t - LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped - WHERE t.id = vTravelFk - ORDER BY r.`dated` DESC - LIMIT 1; + + SELECT e.id INTO vLastEntryFk + FROM vn.entry e + JOIN vn.travel tr ON tr.id = e.travelFk + WHERE e.supplierFk = vSupplierFk + ORDER BY tr.landed DESC + LIMIT 1; - RETURN IFNULL(vCommission, 0); + IF vLastEntryFk THEN + + SELECT commission INTO vCurrentCommission + FROM vn.entry + WHERE id = vLastEntryFk; + + ELSE + + SELECT commission INTO vCurrentCommission + FROM supplier s + WHERE s.id = vSupplierFk; + + END IF; + + RETURN vCurrentCommission; + + ELSE + + SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission + FROM travel t + LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped + WHERE t.id = vTravelFk + ORDER BY r.`dated` DESC + LIMIT 1; + + RETURN IFNULL(vCommission, 0); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33673,6 +30730,35 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `validationCode` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `validationCode`(vString VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vTail VARCHAR(3); + DECLARE vCode INT; + + SET vTail = LEFT(LPAD(vString,3,'0'),3); + + SET vCode = (ASCII(MID(vTail,1,1)) * ASCII(MID(vTail,2,1)) * ASCII(MID(vTail,3,1))) mod 1000; + + RETURN vCode; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `workerIsBoss` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -33735,9 +30821,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -33748,21 +30834,22 @@ BEGIN DECLARE vLastIn DATETIME; DECLARE vDayStayMax INT; DECLARE vHasDirectionOut INT; + DECLARE vLastInsertedId INT; SELECT dayStayMax INTO vDayStayMax - FROM vn.workerTimeControlParams; + FROM workerTimeControlParams; - SELECT vn.timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM workerTimeControl WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - UPDATE vn.workerTimeControl wtc + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' @@ -33771,25 +30858,28 @@ BEGIN ELSE IF vDirection = 'in' THEN SELECT COUNT(*) INTO vHasDirectionOut - FROM vn.workerTimeControl wtc + FROM workerTimeControl wtc WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - UPDATE vn.workerTimeControl wtc + UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - + END IF; END IF; INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - -RETURN LAST_INSERT_ID(); + SET vLastInsertedId = LAST_INSERT_ID(); + + CALL workerTimeControlSOWP(vUserFk, vTimed); + + RETURN vLastInsertedId; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34218,7 +31308,7 @@ BEGIN -- Establecemos los almacenes y las fechas que van a entrar al disponible - CALL vn.zoneGetShippedWarehouse(vDate, vAddress, vAgencyMode); + CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; CREATE TEMPORARY TABLE tmp.availableCalc( @@ -34371,23 +31461,28 @@ BEGIN DECLARE vWarehouseOut INT; DECLARE vIsMerchandise BOOL; DECLARE vIsFeedStock BOOL; - + DECLARE vLanded DATE; + DECLARE vBuyerFk INT; + DECLARE vItemName VARCHAR(50); + SELECT entryFk, itemFk, stickers, packing INTO vEntryFk, vItemFk, vStickers, vPacking FROM buy WHERE id = vSelf; - SELECT t.warehouseInFk, t.warehouseOutFk - INTO vWarehouse, vWarehouseOut + SELECT t.warehouseInFk, t.warehouseOutFk, t.landed + INTO vWarehouse, vWarehouseOut, vLanded FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.id = vEntryFk; - SELECT k.merchandise INTO vIsMerchandise + SELECT k.merchandise, it.workerFk, i.longName + INTO vIsMerchandise, vBuyerFk, vItemName FROM itemCategory k JOIN itemType it ON it.categoryFk = k.id JOIN item i ON i.typeFk = it.id WHERE i.id = vItemFk; + IF vIsMerchandise THEN REPLACE bi.rotacion SET Id_Article = vItemFk, @@ -34410,6 +31505,20 @@ BEGIN CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); END IF; END IF; + + -- Aviso al comprador de modificacion de entrada en Barajas + IF (SELECT isBuyerToBeEmailed FROM warehouse WHERE id = vWarehouse) + AND vLanded = CURDATE() + AND vBuyerFk != account.myUserGetId() + THEN + + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E ',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName), + 'Este email se ha generado automáticamente'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34860,7 +31969,7 @@ BEGIN ENGINE = MEMORY SELECT vItemFk itemFk; - CALL ticketCalculate(vLanded, vAddressFk, vAgencyModeFk); + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; END ;; DELIMITER ; @@ -34886,7 +31995,7 @@ proc: BEGIN /** * Calcula los articulos disponibles y sus precios * - * @table tmp.item(itemFk) Listado de artículos a calcular + * @table tmp.item(itemFk) Listado de artículos a calcular * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia @@ -34906,7 +32015,7 @@ proc: BEGIN DECLARE vZoneFk INT; DECLARE vDone BOOL; DECLARE cTravelTree CURSOR FOR - SELECT id, warehouseFk, shipped FROM tmp.zoneGetShipped; + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -34915,7 +32024,7 @@ proc: BEGIN SELECT clientFk INTO vClient FROM address WHERE id = vAddressFk; - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot( @@ -34982,7 +32091,7 @@ proc: BEGIN LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible JOIN origin o ON o.id = i.originFk JOIN ( - SELECT MIN(price) price, itemFk, MIN(priceKg) priceKg + SELECT MIN(price) price, itemFk, priceKg FROM tmp.ticketComponentPrice GROUP BY itemFk ) bl ON bl.itemFk = b.itemFk @@ -34998,9 +32107,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -35020,6 +32129,7 @@ proc: BEGIN * packing, grouping, groupingMode, buyFk, typeFk) * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) */ + DECLARE vClientFk INT; DECLARE vGeneralInflationCoefficient INT DEFAULT 1; DECLARE vMinimumDensityWeight INT DEFAULT 167; @@ -35069,9 +32179,9 @@ proc: BEGIN LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, z.warehouseFk + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk FROM priceFixed pf - JOIN zone z ON z.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0 + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk @@ -35938,15 +33048,14 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) BEGIN - -- Bernat: WORKING IN THIS FILE DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; CREATE TEMPORARY TABLE tmp.clientPackagingOverstock ENGINE = MEMORY @@ -35957,10 +33066,8 @@ BEGIN sum(GotfromClient) - sum(SenttoClient), sum(InvoicedtoClient) - sum(InvoicedfromClient) ) as abonables - - FROM - ( - + FROM + ( SELECT t.*, IF(@month = month, 0, 1) monthEnd, @month := month @@ -35977,10 +33084,8 @@ BEGIN x.refFk as invoice, month(shipped) month, x.companyFk - FROM ( - SELECT t.id, t.shipped, IFNULL(pe.equivalentFk, s.itemFk) itemFk, @@ -35991,16 +33096,14 @@ BEGIN t.refFk, @month := 0 month, t.companyFk - FROM vn.sale s - JOIN vn.ticket t on t.id = s.ticketFk - JOIN vn2008.Cubos c ON c.item_id = s.itemFk - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = s.itemFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk + JOIN packaging p ON p.itemFk = s.itemFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk WHERE t.clientFk = vClientFk AND t.shipped > '2017-11-30' - AND c.Retornable - + AND p.isPackageReturnable UNION ALL - SELECT NULL, '2017-11-30', IFNULL(pe.equivalentFk, tps.itemFk) itemFk, @@ -36012,13 +33115,11 @@ BEGIN NULL, NULL - FROM vn.ticketPackagingStartingStock tps - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = tps.itemFk + FROM ticketPackagingStartingStock tps + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk WHERE tps.clientFk = vClientFk AND tps.isForgetable = FALSE - UNION ALL - SELECT t.id, t.shipped, IFNULL(pe.equivalentFk, p.itemFk) itemFk, @@ -36029,22 +33130,19 @@ BEGIN NULL AS refFk, NULL, t.companyFk - FROM vn.ticketPackaging tp - JOIN vn.ticket t on t.id = tp.ticketFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = p.itemFk + FROM ticketPackaging tp + JOIN ticket t on t.id = tp.ticketFk + JOIN packaging p ON p.id = tp.packagingFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk WHERE t.clientFk = vClientFk AND t.shipped > '2017-11-21' ) x - JOIN vn.item i ON x.itemFk = i.id + JOIN item i ON x.itemFk = i.id GROUP BY x.id, x.itemFk - ) t ORDER BY itemFk, shipped DESC ) t2 - GROUP BY itemFk - -; + GROUP BY itemFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36229,183 +33327,137 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) -BEGIN - -- BERNAT: WORKING IN THIS FILE - DECLARE vTravelNew INT; - DECLARE vEntryNew INT; - DECLARE vDone BIT DEFAULT 0; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM vn.entry e - JOIN vn.travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE vRsBuy CURSOR FOR - SELECT b.* - FROM vn.buy b - JOIN vn.entry e - ON b.entryFk = e.id - WHERE e.travelFk = vTravelNew and b.entryFk=entryNew - ORDER BY e.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - INSERT INTO vn.travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg - FROM vn.travel - WHERE id = vTravelFk; - - SET vTravelNew = LAST_INSERT_ID(); - SET vDone = 0; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO vn.entry (supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vTravelNew, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM vn.entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - /* INSERT INTO vn.buy ( - entryFk, - itemFk, - amount, - buyingValue, - quantity, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isCkecked) - SELECT - vEntryNew, - itemFk, - amount, - buyingValue, - quantity, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isCkecked - FROM buy - WHERE entryFk = vAuxEntryFk;*/ - - INSERT INTO vn2008.Compres (Id_Entrada, - Id_Article, - Cantidad, - Costefijo, - Id_Cubo, - Etiquetas, - Portefijo, - Embalajefijo, - Comisionfija, - Packing, - `grouping`, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP, - Productor, - Vida, - punteo) - SELECT vEntryNew, - Id_Article, - Cantidad, - Costefijo, - Id_Cubo, - Etiquetas, - Portefijo, - Embalajefijo, - Comisionfija, - Packing, - `grouping`, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP, - Productor, - Vida, - punteo - FROM vn2008.Compres - WHERE Id_Entrada = vAuxEntryFk; - - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - CLOSE vRsEntry; - COMMIT; +BEGIN + + DECLARE vTravelNew INT; + DECLARE vEntryNew INT; + DECLARE vDone BIT DEFAULT 0; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM entry e + JOIN travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE vRsBuy CURSOR FOR + SELECT b.* + FROM buy b + JOIN entry e + ON b.entryFk = e.id + WHERE e.travelFk = vTravelNew and b.entryFk=entryNew + ORDER BY e.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vTravelNew = LAST_INSERT_ID(); + SET vDone = 0; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry (supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vTravelNew, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + + INSERT INTO buy (entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked + FROM buy + WHERE entryFk = vAuxEntryFk; + + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + CLOSE vRsEntry; + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36435,6 +33487,175 @@ BEGIN FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_new` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_new`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vTicketLiters INT; + DECLARE vTicketLines INT; + DECLARE vTicketFk INT; + DECLARE vIsTicketCollected BOOLEAN; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vVolumetryLiters INT; + DECLARE vVolumetryLines INT; + DECLARE vVolumetryFk INT; + DECLARE vVolumetryLevel INT; + DECLARE vVolumetryLitersMax INT; + DECLARE vVolumetryLinesMax INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + + DECLARE cVolumetry CURSOR FOR + SELECT level, liters, `lines` + FROM vn.collectionVolumetry + ORDER BY `level`; + + DECLARE cTicket CURSOR FOR + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE pb.problems = 0 + AND tc.ticketFk IS NULL + AND s.isPreparable + ORDER BY pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC + LIMIT vMaxTickets; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + SELECT COUNT(*), sum(liters), sum(`lines`) + INTO vMaxTickets, vVolumetryLitersMax, vVolumetryLinesMax + FROM vn.collectionVolumetry; + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + -- Empieza el bucle + OPEN cVolumetry; + OPEN cTicket; + + DROP TEMPORARY TABLE IF EXISTS tmp.kk; + CREATE TEMPORARY TABLE tmp.kk + SELECT pb.Id_Ticket ticketFk,pb.Hora, pb.Minuto, + pb.lines, + pb.m3 * 1000 liters + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE pb.problems = 0 + AND tc.ticketFk IS NULL + AND s.isPreparable + ORDER BY pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC + LIMIT vMaxTickets; + + FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters; + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + IF NOT vDone THEN + + INSERT INTO vn.collection + SET workerFk = account.myUserGetId(); + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + END IF; + + bucle:WHILE NOT vDone DO + + IF (vVolumetryLitersMax < vTicketLiters OR vVolumetryLinesMax < vTicketLines) AND vVolumetryLevel > 1 THEN + LEAVE bucle; + END IF; + + SELECT COUNT(*) INTO vIsTicketCollected + FROM vn.ticketCollection + WHERE ticketFk = vTicketFk + AND collectionFk = vCollectionFk; + + IF vIsTicketCollected THEN + + UPDATE vn.ticketCollection + SET level = CONCAT(level, vVolumetryLevel) + WHERE ticketFk = vTicketFk + AND collectionFk = vCollectionFk; + + ELSE + + INSERT INTO vn.ticketCollection + SET collectionFk = vCollectionFk, + ticketFk = vTicketFk, + level = vVolumetryLevel; + + INSERT INTO vncontrol.inter + SET state_id = vStateFk, + Id_Ticket = vTicketFk, + Id_Trabajador = account.myUserGetId(); + + END IF; + + SET vVolumetryLitersMax = GREATEST(0,vVolumetryLitersMax - vVolumetryLiters); + SET vVolumetryLinesMax = GREATEST(0,vVolumetryLinesMax - vVolumetryLines); + SET vTicketLiters = GREATEST(0,vTicketLiters - vVolumetryLiters); + SET vTicketLines = GREATEST(0,vTicketLines - vVolumetryLines); + + IF vVolumetryLitersMax = 0 OR vVolumetryLinesMax = 0 THEN + LEAVE bucle; + END IF; + + IF vTicketLiters > 0 OR vTicketLines > 0 THEN + + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + ELSE + + FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters; + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + END IF; + + END WHILE; + + SELECT vCollectionFk; + + CLOSE cVolumetry; + CLOSE cTicket; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36852,9 +34073,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36896,9 +34117,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36974,6 +34195,139 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_doCalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() +proc: BEGIN +/** + * Recalculates the department tree. + */ + DECLARE vIsChanged BOOL; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.department_doCalc'); + RESIGNAL; + END; + + IF !GET_LOCK('vn.department_doCalc', 0) THEN + LEAVE proc; + END IF; + + SELECT isChanged INTO vIsChanged + FROM department_recalc; + + IF vIsChanged THEN + UPDATE department_recalc SET isChanged = FALSE; + CALL vn.department_calcTree; + END IF; + + DO RELEASE_LOCK('vn.department_doCalc'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_getLeaves` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM department + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM department g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM department + WHERE parentFk <=> vParentFk; + END IF; + + SELECT d.id, + d.`name`, + d.parentFk, + d.sons + FROM department d + JOIN tNodes n ON n.id = d.id + ORDER BY depth, `name`; + + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `duaEntryValueUpdate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -37028,7 +34382,6 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) BEGIN - -- BERNAT: WORKING IN THIS FILE DECLARE done BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; @@ -37093,6 +34446,88 @@ BEGIN SET ASIEN = vASIEN WHERE id = vDuaFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaInvoiceInBooking__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking__`(vDuaFk INT) +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vASIEN BIGINT DEFAULT 0; + DECLARE vCounter INT DEFAULT 0; + + DECLARE rs CURSOR FOR + SELECT e.invoiceInFk + FROM entry e + JOIN duaEntry de ON de.entryFk = e.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE de.duaFk = vDuaFk + AND de.customsValue + AND ii.isBooked = FALSE; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + UPDATE invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + SET ii.isBooked = TRUE, + ii.booked = IFNULL(ii.booked,d.booked), + ii.operated = IFNULL(ii.operated,d.operated), + ii.issued = IFNULL(ii.issued,d.issued), + ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), + e.isConfirmed = TRUE + WHERE d.id = vDuaFk; + + SELECT IFNULL(ASIEN,0) INTO vASIEN + FROM dua + WHERE id = vDuaFk; + + FETCH rs INTO vInvoiceFk; + + WHILE NOT done DO + + CALL invoiceInBookingMain(vInvoiceFk); + + IF vCounter > 0 OR vASIEN > 0 THEN + + UPDATE XDiario x + JOIN config c ON c.ASIEN = x.ASIEN + SET x.ASIEN = vASIEN; + + ELSE + + SELECT ASIEN INTO vASIEN FROM config; + + END IF; + + SET vCounter = vCounter + 1; + + FETCH rs INTO vInvoiceFk; + + END WHILE; + + CLOSE rs; + + UPDATE dua + SET ASIEN = vASIEN + WHERE id = vDuaFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38254,32 +35689,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( vWarehouse TINYINT, vRefresh BOOL) BEGIN - - /*deprecated usar vn.itemGetVisibleAvailable - jgf 2019/09/10 */ - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - - -- FIXME: Android app is always passing %TRUE for #vRefresh, this leads to DB performance issues - CALL cache.visible_refresh(vVisibleCalc, FALSE /*vRefresh*/, vWarehouse); - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); - - SELECT a.Id_Article, a.Article, a.Medida, a.Tallos, - a.caja, O.Abreviatura AS origen, a.Color, tipo_id, - an.Nicho, a.Categoria, p.`name` AS producer, - v.visible, av.available, an.reserve - FROM vn2008.Articles a - LEFT JOIN vn2008.Articles_nicho an - ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = a.Id_Article AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = a.Id_Article AND av.calc_id = vAvailableCalc - LEFT JOIN vn2008.Origen O - ON O.id = a.id_origen - LEFT JOIN vn2008.producer p - ON p.producer_id = a.producer_id - WHERE (vItem IS NULL OR a.Id_Article = vItem); + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39299,11 +36710,11 @@ BEGIN FECREGCON, empresa_id ) - SELECT vBookNumber ASIEN, + SELECT vBookNumber ASIEN, n.bookEntried FECHA, tc.code SUBCTA, s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, + ROUND(tc.rate/100 * SUM(it.taxableBase) + 0.0001, 2) EURODEBE, SUM(it.taxableBase) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -41508,65 +38919,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( vWarehouse TINYINT, vRefresh BOOL) BEGIN - - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - DECLARE vVisibleAltillo INT; - - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); - CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - - - - SELECT visible INTO vVisibleAltillo - FROM vn.itemShelvingStock - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - IF vRefresh THEN - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT vItem item_id, 0 stock, 0 visible; - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - vi.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN vn2008.tmp_item v - ON v.item_id = i.id - LEFT JOIN cache.available av - ON av.calc_id = vAvailableCalc AND av.item_id = i.id - LEFT JOIN cache.visible vi - ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id - LEFT JOIN cache.stock st - ON st.warehouse_id = vWarehouse AND st.item_id = i.id - WHERE (vItem IS NULL OR i.id = vItem); - - ELSE - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - v.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = i.id AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = i.id AND av.calc_id = vAvailableCalc - WHERE (vItem IS NULL OR i.id = vItem); - - END IF; - + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43485,6 +40839,84 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_getVisibleAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + DECLARE vVisibleAltillo INT; + + CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); + CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); + + SELECT visible INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItem + AND warehouseFk = vWarehouse; + + IF vRefresh THEN + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT vItem item_id, 0 stock, 0 visible; + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + vi.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN vn2008.tmp_item v + ON v.item_id = i.id + LEFT JOIN cache.available av + ON av.calc_id = vAvailableCalc AND av.item_id = i.id + LEFT JOIN cache.visible vi + ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id + LEFT JOIN cache.stock st + ON st.warehouse_id = vWarehouse AND st.item_id = i.id + WHERE (vItem IS NULL OR i.id = vItem); + + ELSE + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + v.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN cache.visible v + ON v.item_id = i.id AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av + ON av.item_id = i.id AND av.calc_id = vAvailableCalc + WHERE (vItem IS NULL OR i.id = vItem); + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ledger_next` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43612,6 +41044,48 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mail_insert` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mail_insert`( + vSender VARCHAR(50), + vReplyTo VARCHAR(50), + vSubject VARCHAR(50), + vBody VARCHAR(255)) +BEGIN + + DECLARE vIsRepeated BOOLEAN; + + SELECT COUNT(*) INTO vIsRepeated + FROM vn.mail + WHERE creationDate >= CURDATE() + AND sender = vSender + AND `replyTo` = vReplyTo + AND `subject` = vSubject; + + IF NOT vIsRepeated THEN + + INSERT INTO vn.mail SET + `sender` = vSender, + `replyTo` = vReplyTo, + `subject` = vSubject, + `body` = vBody; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `makeNewItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44764,6 +42238,56 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rangeDateInfo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rangeDateInfo`(vStarted DATE, vEnded DATE) +BEGIN +/** + * Crea una tabla temporal con las fechas + * desde una fecha inicial a una final + * @param vStarted fecha inicial + * @param vEnded fecha final + */ + DECLARE vDated DATE DEFAULT vStarted; + + DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; + CREATE TEMPORARY TABLE tmp.rangeDate( + `dated` DATE, + `period` INT, + `month` INT, + `year` INT, + `day` INT, + `week` INT, + `yearMonth` INT + ) + ENGINE = MEMORY; + + WHILE vDated <= vEnded DO + INSERT INTO tmp.rangeDate + SET `dated` = vDated, + `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), + `month` = MONTH(vDated), + `year` = YEAR(vDated), + `day` = DAY(vDated), + `week` = WEEK(vDated, 1), + `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); + + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); + END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `refund` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44808,8 +42332,7 @@ BEGIN WHERE id = vOriginTicket; SELECT id INTO vZoneFk - FROM zone WHERE agencyModeFk = vRefundAgencyMode - ORDER BY (warehouseFk = vWarehouse) DESC + FROM zone WHERE agencyModeFk = vRefundAgencyMode LIMIT 1; INSERT INTO vn2008.Tickets ( @@ -45434,92 +42957,92 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleMove`(IN vSaleFk BIGINT, IN vQuantity BIGINT) BEGIN +-- JGF is working in this file 2019-12-20 + DECLARE vclientFk INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk INT; + DECLARE vCompanyFk INT; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vNewTicket BIGINT; + DECLARE vNewSale BIGINT; + DECLARE vLanded DATE; + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + DECLARE vAuxId INT; + DECLARE vNumLine INT; + DECLARE vItemFk INT; - DECLARE vclientFk INT; - DECLARE vShipped DATE; - DECLARE vWarehouseFk INT; - DECLARE vCompanyFk INT; - DECLARE vAddressFk INT; - DECLARE vAgencyModeFk INT; - DECLARE vNewTicket BIGINT; - DECLARE vNewSale BIGINT; - DECLARE vLanded DATE; - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - DECLARE vAuxId INT; - DECLARE vNumLine INT; - DECLARE vItemFk INT; - - SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id + SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id INTO vclientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgencyModeFk,vLanded,vAuxId FROM ticket t JOIN sale s ON s.ticketFk=t.id WHERE s.id = vSaleFk; - SET vDateStart = TIMESTAMP(vShipped); - SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); + SET vDateStart = TIMESTAMP(vShipped); + SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); - SELECT t.id INTO vNewTicket + SELECT t.id INTO vNewTicket FROM ticket t JOIN ticketState ts ON ts.ticketFk=t.id WHERE t.addressFk = vAddressFk AND t.warehouseFk = vWarehouseFk - AND t.agencyModeFk = vAgencyModeFk - AND t.landed <=> vLanded - AND t.shipped BETWEEN vDateStart AND vDateEnd - AND t.refFk IS NULL - AND t.clientFk <> 1118 - AND t.id <> vAuxId - AND IFNULL(ts.alertLevel,0) = 0 + AND t.agencyModeFk = vAgencyModeFk + AND t.landed <=> vLanded + AND t.shipped BETWEEN vDateStart AND vDateEnd + AND t.refFk IS NULL + AND t.clientFk <> 1118 + AND t.id <> vAuxId + AND IFNULL(ts.alertLevel,0) = 0 LIMIT 1; -IF vNewTicket IS NULL - THEN + IF vNewTicket IS NULL THEN CALL vn.ticket_Clone(vAuxId, vNewTicket); - /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ - END IF; + /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ + END IF; - INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) - SELECT vNewTicket, getWorker(), s.id - FROM state s - WHERE s.code = 'FIXING'; + INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) + SELECT vNewTicket, getWorker(), s.id + FROM state s + WHERE s.code = 'FIXING'; - /*parche para campapña, eliminar y modificar el front*/ -SELECT COUNT(id) INTO vNumLine - FROM sale s - WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); - - IF vNumLine = 0 THEN - - INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + /*parche para campapña, eliminar y modificar el front*/ + SELECT COUNT(id) INTO vNumLine FROM sale s - WHERE s.id = vSaleFk; + WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); - SELECT LAST_INSERT_ID() INTO vNewSale; + IF vNumLine = 0 THEN - INSERT INTO saleComponent(saleFk, componentFk, `value`) - SELECT vNewSale, componentFk, `value` - FROM saleComponent - WHERE saleFk = vSaleFk; - -ELSE IF vQuantity <> 0 THEN + 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 + WHERE saleFk = vSaleFk; + + ELSE + IF vQuantity <> 0 THEN - SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; - UPDATE sale SET quantity = vQuantity - WHERE ticketFk = vNewTicket AND itemFk = vItemFk; + SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; + UPDATE sale SET quantity = vQuantity + WHERE ticketFk = vNewTicket AND itemFk = vItemFk; -END IF; -END IF; + END IF; + END IF; END ;; DELIMITER ; @@ -45819,7 +43342,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT) proc: BEGIN - +/** + * Actualiza los componentes + * + * @param vSale Delivery date + * @param vOption indica en que componente pone el descuadre, NULL en casos habituales + * @return tmp.ticketLot(warehouseFk, available, itemFk, buyFk) + * @return tmp.sale(saleFk, warehouseFk) + */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; @@ -46731,19 +44261,18 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stowawayUnBoarding` */; +/*!50003 DROP PROCEDURE IF EXISTS `stowaway_unboarding` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stowawayUnBoarding`(vShipFk INT, vStowawayFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) BEGIN - DECLARE vWorker VARCHAR(255); DELETE FROM stowaway @@ -46754,11 +44283,13 @@ BEGIN WHERE code = 'BOARDING' AND ticketFk = vShipFk; DELETE FROM sale - WHERE ticketFk = vShipFk AND itemFk = 98 AND concept = CONCAT('POLIZÓN! ',vStowawayFk); + WHERE ticketFk = vShipFk + AND itemFk = 98 + AND concept = CONCAT('POLIZÓN! ',vStowawayFk); SELECT u.`name` INTO vWorker - FROM account.user u JOIN vn.worker w ON w.userFk = u.id - WHERE w.id = vn2008.Averiguar_ComercialCliente_IdTicket_Id(vStowawayFk); + FROM account.user u JOIN worker w ON w.userFk = u.id + WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; END ;; @@ -47094,32 +44625,42 @@ BEGIN DECLARE vAddress INT; DECLARE vLanded DATE; DECLARE vAgency INT; + DECLARE vZoneFk INT; REPLACE INTO orderTicket(orderFk,ticketFk) SELECT orderFk, vTicketNew FROM orderTicket WHERE ticketFk = vTicketOld; - - SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk - INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk FROM vn.agencyMode a JOIN vn.ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicketNew; + + IF vLanded IS NULL THEN + CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed, + t.zone = zgl.zoneFk + WHERE t.id = vTicketNew; + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + END IF; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CALL zoneGetShippedWarehouse(vLanded, vAddress, vAgencyMode); - DELETE FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouse; - - CALL buyUltimate(vWarehouse, vShipped); -- rellena la tabla tmp.buyUltimate con la ultima compra + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - CALL ticketComponentCalculate(vAddress,vAgencyMode); + CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); -- Bionizamos lineas con Preu = 0 DROP TEMPORARY TABLE IF EXISTS tmp.sale; @@ -47141,14 +44682,6 @@ BEGIN AND s.price > 0; CALL ticketComponentUpdateSale(6); - - IF vLanded IS NULL THEN - CALL zoneGetLanded(vShipped, vAddress, vAgency,vWarehouse); - UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk - SET t.landed = zgl.landed - WHERE t.id = vTicketNew; - END IF; -- Log CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); @@ -47307,18 +44840,15 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vLanded DATE; - DECLARE vZoneFk INT; - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - + DECLARE vZoneFk INT; SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale WHERE id = vSale; - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; @@ -47360,9 +44890,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -47374,18 +44904,15 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vLanded DATE; DECLARE vZoneFk INT; - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - - + SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale WHERE id = vSale; - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; @@ -47510,9 +45037,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -47538,7 +45065,7 @@ BEGIN SELECT ticketFk FROM tmp.ticketClosure; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -47604,9 +45131,6 @@ BEGIN CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); -- Facturar si está contabilizado IF vIsTaxDataChecked THEN - - -- JGF cau 12220 - -- IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN CALL invoiceOut_newFromClient( vClientFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), @@ -47614,15 +45138,13 @@ BEGIN vCompanyFk, NULL, vNewInvoiceId); - /*ELSE - CALL invoiceOut_newFromTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), NULL, vNewInvoiceId); - END IF;*/ - END IF; ELSE -- Albaran_print CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); + -- Comentar al pasar a nuevo cierre + INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); + -- INSERT INTO END IF; -- ticketClosure end @@ -47887,23 +45409,23 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( vAddressFk INT, vAgencyModeFk INT) proc: BEGIN -- OBSOLETO usar catalog_componentCalculate /** - * Calcula los componentes de un ticket + * Calcula los componentes de un ticket * * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id del modo de agencia @@ -48155,7 +45677,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48165,7 +45687,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate__`( vTicketFk INT, vClientFk INT, vAgencyModeFk INT, @@ -48204,7 +45726,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48214,7 +45736,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview__`( vTicketFk INT, vLanded DATE, vAddressFk INT, @@ -48311,7 +45833,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48321,7 +45843,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference__`( vTicketFk INT, vLanded DATE, vAddressFk INT, @@ -48643,9 +46165,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48657,7 +46179,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( ,vAddressFk INT ,vAgencyModeFk INT ,vRouteFk INT - ,vLanded DATE + ,vlanded DATE ,vUserId INT ,OUT vNewTicket INT) BEGIN @@ -48680,9 +46202,9 @@ BEGIN WHERE clientFk = vClientId AND isDefaultAddress; END IF; - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; INSERT INTO vn2008.Tickets ( @@ -48699,14 +46221,14 @@ BEGIN ) SELECT vClientId, - IFNULL(vShipped,vLanded), + vShipped, a.id, IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), a.nickname, vWarehouseFk, IF(vRouteFk,vRouteFk,NULL), vCompanyFk, - vLanded, + vlanded, vZoneFk FROM address a JOIN agencyMode am ON am.id = a.agencyModeFk @@ -48740,9 +46262,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48754,7 +46276,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( ,vAddressFk INT ,vAgencyModeFk INT ,vRouteFk INT - ,vLanded DATE + ,vlanded DATE ,vUserId INT ,OUT vNewTicket INT) BEGIN @@ -48773,9 +46295,9 @@ BEGIN IF vAgencyModeFk IS NOT NULL THEN - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; IF vZoneFk IS NULL OR vZoneFk = 0 THEN @@ -48796,14 +46318,14 @@ BEGIN ) SELECT vClientId, - IFNULL(vShipped,vLanded), + vShipped, a.id, vAgencyModeFk, a.nickname, vWarehouseFk, IF(vRouteFk,vRouteFk,NULL), vCompanyFk, - vLanded, + vlanded, vZoneFk FROM address a JOIN agencyMode am ON am.id = a.agencyModeFk @@ -50543,9 +48065,10 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vLanded DATE; DECLARE vIsTicketEditable BOOLEAN; + DECLARE vZoneFk INTEGER; - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE - INTO vIsTicketEditable + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket WHERE id = vTicketFk; @@ -50567,7 +48090,7 @@ proc: BEGIN WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -50625,10 +48148,11 @@ proc: BEGIN DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vLanded DATE; + DECLARE vZoneFk INTEGER; IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE - INTO vIsTicketEditable + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket WHERE id = vTicketFk; END IF; @@ -50650,7 +48174,7 @@ proc: BEGIN WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -50687,15 +48211,15 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - -- BERNAT: WORKING IN THIS FILE + /** * Horas que debe trabajar un empleado según contrato y día. * @param vDatedFrom workerTimeControl @@ -50707,7 +48231,9 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; - + + CALL rangeDateInfo(vDatedFrom, vDatedTo); + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate SELECT dated, businessFk, @@ -50724,7 +48250,7 @@ BEGIN type, permissionrate, hoursWeek - FROM(SELECT t.dated, + FROM(SELECT rd.dated, b.business_id businessFk, w.userFk, bl.department_id departmentFk, @@ -50734,8 +48260,8 @@ BEGIN cs.type, cs.permissionRate, cl.hours_week hoursWeek - FROM vn.time t - LEFT JOIN postgresql.business b ON t.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) + FROM tmp.rangeDate rd + LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id @@ -50745,10 +48271,10 @@ BEGIN LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id - LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(t.dated)+1 - LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = t.dated + LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 + LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id - WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY w.userFk,dated )sub; @@ -50778,6 +48304,7 @@ BEGIN t.type = 'Festivo' WHERE t.type IS NULL; +DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50949,34 +48476,38 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - -/** - * Horas totales trabajadas a partir de las fichadas, tiene en cuenta los descansos y fichadas impares - * (si hay fichadas impares nop devuelve info) - * @param vDatedFrom workerTimeControl - * @param vDatedTo workerTimeControl - * @table tmp.user(userFk) - * @return tmp.timeControlCalculate - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - - CREATE TEMPORARY TABLE tmp.timeControlCalculate - SELECT userFk, - dated, - IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, - SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, - @timeWork / 3600 timeWorkDecimal - FROM (SELECT wtc.userFk, - DATE(wtc.timed) dated, - SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))) timeWork - FROM vn.workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo - GROUP BY wtc.userFk,dated - ORDER BY userFk,dated - )sub - WHERE sub.timeWork > 0; + SET @vIsOdd := TRUE; + SET @vUser := NULL; + SET @vDated := NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + + CREATE TEMPORARY TABLE tmp.timeControlCalculate + SELECT userFk, + dated, + IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, + SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, + @timeWork / 3600 timeWorkDecimal + FROM (SELECT SUM(timeWork) timeWork, + userFk, + dated + FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), + IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), + IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), + IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), + IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, + IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, + wtc.userFk, + wtc.timed timed, + direction + FROM workerTimeControl wtc + JOIN tmp.`user` w ON w.userFk = wtc.userFk + WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo + ORDER BY userFk, timed + ) sub + GROUP BY userFk, dated + ORDER BY userFk, dated + )sub2; END ;; DELIMITER ; @@ -52401,16 +49932,17 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - SELECT vn.workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); - CALL vn.workerTimeControlSOWP(vUserFk, vTimed); + + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52511,6 +50043,9 @@ proc: BEGIN DECLARE vTimedWorked INT; DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; DECLARE vDepartmentFk INT; + DECLARE vTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vBody VARCHAR(255) DEFAULT NULL; SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax @@ -52524,13 +50059,25 @@ proc: BEGIN SELECT MAX(timed) INTO vLastOut FROM vn.workerTimeControl WHERE userFk = vUserFk - AND direction = 'out'; + AND direction = 'out'; + + SELECT email INTO vTo + FROM vn.worker w + WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); + + SELECT CONCAT(firstName,' ',lastName) INTO vUserName + FROM vn.worker w + WHERE w.id = vUserFk; + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA -- VERIFICAR DESCANSO DIARIO IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52541,7 +50088,10 @@ proc: BEGIN AND timed >= vLastIn ) THEN SELECT "Dias con fichadas impares" AS problem; - LEAVE proc; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; END IF; -- VERIFICAR VACACIONES @@ -52559,7 +50109,11 @@ proc: BEGIN IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; + END IF; @@ -52574,7 +50128,11 @@ proc: BEGIN AND IFNULL(b.date_end,vDated) >= vDated ) = 0 THEN SELECT "No hay un contrato en vigor" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL @@ -52593,6 +50151,9 @@ proc: BEGIN IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52609,6 +50170,9 @@ proc: BEGIN IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52624,7 +50188,10 @@ proc: BEGIN WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk ) = 0 THEN SELECT "No perteneces a este departamento." AS problem; - LEAVE proc; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; END IF; END IF; @@ -53532,98 +51099,7 @@ BEGIN * @select Listado de agencias disponibles */ - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM ( - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - zi.isIncluded, - z.warehouseFk, - z.id zoneFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - JOIN agencyMode am ON am.id = z.agencyModeFk - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND TIMESTAMPADD(DAY,-z.travelingDays, vLanded) >= CURDATE() - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC, zi.isIncluded DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - ORDER BY shipped) t - GROUP BY agencyModeFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetFirstShipped` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetFirstShipped`(vAgencyModeFk INT, vAddress INT, vWarehouseFk INT) -BEGIN -/** -* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse -* -* @param vAgencyMode id de la agencia en vn.agencyMode -* @param vAddress id de la direccion -* @param vWarehouse id del warehouse -* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida -*/ - - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - SELECT * FROM ( - SELECT TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) shipped, - zc.delivered landed, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - AND TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) >= CURDATE() - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY landed ASC, zgFather.depth DESC) t - HAVING isIncluded > 0 LIMIT 1; + CALL zone_getAgency(vAddress,vLanded); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53634,58 +51110,23 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) BEGIN /** * Devuelve una tabla temporal con el dia de recepcion para vShipped. * * @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia +* @param vAddress Id de consignatario, %NULL para recogida +* @param vAgencyMode Id agencia * @table tmp.zoneGetLanded Datos de recepción */ - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT - id zoneFk, - vShipped shipped, - delivered landed, - vWarehouseFk warehouseFk, - agencyModeFk, - isIncluded - FROM ( - SELECT zi.isIncluded, zc.delivered, z.id, z.agencyModeFk - FROM vn.zoneGeo zgSon - JOIN vn.zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = TIMESTAMPADD(DAY,z.travelingDays, vShipped) - AND IF(vShipped = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - ORDER BY zgFather.depth DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - LIMIT 1; + CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53696,15 +51137,16 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) BEGIN /** + * OBSOLETO usar zone_getShippedWarehouse * Devuelve la mínima fecha de envía para cada warehouse * * @param vLanded La fecha de recepcion @@ -53712,41 +51154,10 @@ BEGIN * @param vAgencyModeFk Id de la agencia * @return tmp.zoneGetShipped */ - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - SELECT * FROM ( - SELECT * FROM ( - SELECT z.id zoneFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - vLanded landed, - vWarehouseFk warehouseFk, - z.agencyModeFk, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC, isIncluded DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - ORDER BY shipped) - t - GROUP BY agencyModeFk; + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53773,40 +51184,7 @@ BEGIN * @param vAgencyModeFk Id de la agencia * @return tmp.zoneGetShipped */ - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM ( - SELECT z.id, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - zi.isIncluded,z.warehouseFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, shipped ASC, zgFather.depth DESC, zi.isIncluded DESC) t - GROUP BY warehouseFk, id - HAVING isIncluded > 0 - ORDER BY shipped) t - GROUP BY warehouseFk; + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53877,7 +51255,272 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetWarehouse__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** +* Devuelve el listado de agencias disponibles para la fecha, + * dirección y warehouse pasadas + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddress + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + SELECT * FROM ( + SELECT * FROM ( + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + z.warehouseFk, + zi.isIncluded, + z.id zoneFk + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + JOIN agencyMode am ON am.id = z.agencyModeFk + WHERE zgSon.`id` = vGeoFk + AND delivered = vLanded + AND z.warehouseFk = vWarehouse + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, zgFather.depth DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0) t + GROUP BY agencyModeFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getAgency` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha + * y dirección pasadas. + * + * @param vAddress Id de dirección de envío, %NULL si es recogida + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; + CREATE TEMPORARY TABLE tmp.zoneGetAgency + (INDEX (agencyModeFk)) ENGINE = MEMORY + SELECT am.name agencyMode, + am.description, + z.agencyModeFk, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + TRUE isIncluded, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + GROUP BY agencyModeFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAvailable`(vAddress INT, vLanded DATE) +BEGIN + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT * FROM tmp.zoneOption; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getEvents` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( + vProvinceFk INT, + vPostCode VARCHAR(255), + vAgencyModeFk INT) +BEGIN +/** + * Returns available events for the passed province/postcode and agency. + * + * @param vAgencyModeFk The agency mode id + * @param vProvinceFk The province id + * @param vPostCode The postcode or %NULL to use the province + */ + DECLARE vGeoFk INT; + + IF vPostCode IS NOT NULL THEN + SELECT p.geoFk INTO vGeoFk + FROM postCode p + JOIN town t ON t.id = p.townFk + WHERE p.`code` = vPostCode + AND t.provinceFk = vProvinceFk; + ELSE + SELECT geoFk INTO vGeoFk + FROM province + WHERE id = vProvinceFk; + END IF; + + CALL zone_getFromGeo(vGeoFk); + + IF vAgencyModeFk IS NOT NULL THEN + DELETE t FROM tmp.zone t + JOIN zone z ON z.id = t.id + WHERE z.agencyModeFk != vAgencyModeFk; + END IF; + + SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays + FROM tmp.zone t + JOIN zoneEvent e ON e.zoneFk = t.id; + + SELECT e.zoneFk, e.dated + FROM tmp.zone t + JOIN zoneExclusion e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE tmp.zone; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getFromGeo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getFromGeo`(vGeoFk INT) +BEGIN +/** + * Returns all zones which have the passed geo included. + * + * @param vGeoFk The geo id + * @return tmp.zone(id) The list of zones + */ + DECLARE vChildFk INT DEFAULT vGeoFk; + DECLARE vParentFk INT; + DECLARE vLevel INT DEFAULT 1; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT vGeoFk id, vLevel `level`; + + myLoop: LOOP + SELECT parentFk INTO vParentFk + FROM zoneGeo + WHERE id = vChildFk; + + SET vChildFk = vParentFk; + SET vLevel = vLevel + 1; + + INSERT IGNORE INTO tNodes + SELECT vChildFk, vLevel + FROM DUAL + WHERE vChildFk IS NOT NULL; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + END LOOP; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE tmp.zone + (INDEX (id)) + ENGINE = MEMORY + SELECT id FROM ( + SELECT zoneFk id, isIncluded + FROM ( + SELECT i.zoneFk, i.isIncluded + FROM tNodes n + JOIN zoneIncluded i ON i.geoFk = n.id + ORDER BY zoneFk, n.`level` + ) t + GROUP BY id HAVING isIncluded + ) t; + + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLanded` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -53887,12 +51530,59 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** +* Devuelve una tabla temporal con el dia de recepcion para vShipped. +* +* @param vShipped Fecha de preparacion de mercancia +* @param vAddressFk Id de consignatario, %NULL para recogida +* @param vAgencyModeFk Id agencia +* @param vWarehouseFk vWarehouseFk +* @table tmp.zoneGetLanded Datos de recepción +*/ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForShipment(vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + CREATE TEMPORARY TABLE tmp.zoneGetLanded + ENGINE = MEMORY + SELECT vWarehouseFk warehouseFk, + TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN zoneWarehouse zw ON zw.zoneFk = z.id + WHERE agencyModeFk = vAgencyModeFk + AND zw.warehouseFk = vWarehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves`( vSelf INT, vParentFk INT, vSearch VARCHAR(255) ) -BEGIN +BEGIN DECLARE vIsNumber BOOL; DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; @@ -53976,6 +51666,260 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForLanding` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) +BEGIN +/** + * Gets computed options for the passed zones and delivery date. + * + * @table tmp.zones(id) The zones ids + * @param vLanded The delivery date + * @return tmp.zoneOption The computed options + */ + DECLARE vHour TIME DEFAULT TIME(NOW()); + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.travelingDays, z.travelingDays) travelingDays, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + WHERE ( + e.`type` = 'day' + AND e.dated = vLanded + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(vLanded)) + AND (e.`started` IS NULL OR vLanded >= e.`started`) + AND (e.`ended` IS NULL OR vLanded <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; + + DELETE FROM tTemp + WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() + OR @shipped = CURDATE() AND vHour > `hour`; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE tTemp; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForShipment` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) +BEGIN +/** + * Gets computed options for the passed zones and shipping date. + * + * @table tmp.zones(id) The zones ids + * @param vShipped The shipping date + * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options + */ + DROP TEMPORARY TABLE IF EXISTS tLandings; + CREATE TEMPORARY TABLE tLandings + (INDEX (eventFk)) + ENGINE = MEMORY + SELECT e.id eventFk, + @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, + TIMESTAMPADD(DAY, @travelingDays, vShipped) landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity, + l.travelingDays, + l.landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + JOIN tLandings l ON l.eventFk = e.id + WHERE ( + e.`type` = 'day' + AND e.`dated` = l.landed + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(l.landed)) + AND (e.`started` IS NULL OR l.landed >= e.`started`) + AND (e.`ended` IS NULL OR l.landed <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE + tTemp, + tLandings; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CREATE TEMPORARY TABLE tmp.zoneGetShipped + ENGINE = MEMORY + SELECT * FROM ( + SELECT zo.zoneFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.agencyModeFk + FROM tmp.zoneOption zo + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + JOIN zone z ON z.id = zo.zoneFk + WHERE z.agencyModeFk = vAgencyModeFk + ORDER BY shipped) t + GROUP BY warehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha, + * dirección y almacén pasados. + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.id zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + WHERE zw.warehouseFk + GROUP BY z.agencyModeFk + ORDER BY agencyMode; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Current Database: `vncontrol` @@ -54038,7 +51982,6 @@ CREATE TABLE `inter` ( KEY `ticket` (`Id_Ticket`), KEY `inter_state` (`state_id`), KEY `inter_id` (`Id_Ticket`,`inter_id`) USING BTREE, - CONSTRAINT `currante` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE, CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE @@ -54404,156 +52347,6 @@ USE `bi`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Current Database: `bs` --- - -USE `bs`; - --- --- Final view structure for view `bajasLaborales` --- - -/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `bajasLaborales` AS select `p`.`firstname` AS `firstname`,`p`.`name` AS `name`,`b`.`business_id` AS `business_id`,max(`ce`.`date`) AS `lastDate`,max(ifnull(`b`.`date_end`,curdate())) AS `endContract`,`cs`.`type` AS `type`,cast(count(0) as decimal(10,0)) AS `dias`,`w`.`userFk` AS `userFk` from (((((`postgresql`.`calendar_employee` `ce` join `postgresql`.`business` `b` on((`b`.`business_id` = `ce`.`business_id`))) join `postgresql`.`profile` `pr` on((`pr`.`profile_id` = `b`.`client_id`))) join `postgresql`.`person` `p` on((`p`.`person_id` = `pr`.`person_id`))) join `postgresql`.`calendar_state` `cs` on((`cs`.`calendar_state_id` = `ce`.`calendar_state_id`))) join `vn`.`worker` `w` on((`w`.`id` = `p`.`id_trabajador`))) where ((`ce`.`date` >= (curdate() + interval -(1) year)) and (`cs`.`type` not in ('Vacaciones','Vacaciones 1/2 día','Compensar','Festivo'))) group by `p`.`firstname`,`p`.`name`,`cs`.`type` having (`endContract` >= curdate()) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `lastIndicators` --- - -/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,(`i`.`lastYearSales` - `yi`.`lastYearSales`) AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,(`i`.`totalGreuge` - `yi`.`totalGreuge`) AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,(`i`.`latePaymentRate` - `yi`.`latePaymentRate`) AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,(`i`.`countEmployee` - `yi`.`countEmployee`) AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,(`i`.`averageMana` - `yi`.`averageMana`) AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,(`i`.`bankingPool` - `yi`.`bankingPool`) AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,(`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients`) AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,(`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients`) AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,(`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients`) AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,(`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate`) AS `incLastMonthWebBuyingRate`,`i`.`productionHours` AS `productionHours`,`i`.`dailyWorkersCost` AS `dailyWorkersCost`,`i`.`volumeM3` AS `volumeM3`,`i`.`salesValue` AS `salesValue`,`i`.`valueM3` AS `valueM3`,`i`.`hoursM3` AS `hoursM3`,`i`.`workerCostM3` AS `workerCostM3`,`i`.`salesWorkersCostRate` AS `salesWorkersCostRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on((`yi`.`updated` = (select (max(`indicators`.`updated`) + interval -(1) day) from `indicators`)))) where (`i`.`updated` = (select max(`indicators`.`updated`) from `indicators`)) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `m3Silla` --- - -/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `m3Silla` AS select `m3`.`fecha` AS `fecha`,`m3`.`year` AS `year`,`m3`.`month` AS `month`,`m3`.`week` AS `week`,`m3`.`day` AS `day`,`m3`.`dayName` AS `dayName`,cast(sum(`m3`.`m3`) as decimal(10,0)) AS `Volumen`,cast(sum(`m3`.`euros`) as decimal(10,0)) AS `Euros` from `m3` where (`m3`.`warehouseFk` in (1,44)) group by `m3`.`fecha` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `m3analisis` --- - -/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `m3analisis` AS select `m`.`fecha` AS `fecha`,`m`.`year` AS `year`,`m`.`month` AS `month`,`m`.`week` AS `week`,`m`.`day` AS `day`,`m`.`dayName` AS `dayName`,`m`.`Volumen` AS `Volumen`,`m`.`Euros` AS `Euros`,`h`.`Departamento` AS `Departamento`,`h`.`Horas` AS `Horas`,`h`.`Salarios` AS `Salarios`,(`h`.`Horas` / `m`.`Volumen`) AS `tiempoM3`,(`m`.`Euros` / `m`.`Volumen`) AS `valorM3`,(`h`.`Salarios` / `m`.`Volumen`) AS `costeLaboralM3`,(`h`.`Salarios` / `m`.`Euros`) AS `costeEuros`,(`h`.`Salarios` / `h`.`Horas`) AS `precioHora` from (`bs`.`m3Silla` `m` join `bs`.`horasSilla` `h` on((`h`.`Fecha` = `m`.`fecha`))) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `manaSpellersExcluded` --- - -/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `manaSpellersExcluded` AS select `m`.`Id_Trabajador` AS `workerFk` from `mana_spellers_excluded` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `mana_spellers` --- - -/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mana_spellers` AS select `wm`.`workerFk` AS `Id_Trabajador`,`wm`.`size` AS `size`,`wm`.`amount` AS `used`,`wm`.`pricesModifierRate` AS `prices_modifier_rate`,`wm`.`isPricesModifierActivated` AS `prices_modifier_activated`,`wm`.`minRate` AS `minRate`,`wm`.`maxRate` AS `maxRate` from `vn`.`workerMana` `wm` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `mermas` --- - -/*!50001 DROP VIEW IF EXISTS `mermas`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mermas` AS select `w`.`code` AS `Comprador`,`it`.`name` AS `Familia`,`i`.`id` AS `Referencia`,`i`.`name` AS `Item`,`s`.`quantity` AS `Cantidad`,(((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) AS `Coste_Unitario`,(`s`.`quantity` * (((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`)) AS `Importe`,`c`.`name` AS `Cliente`,`s`.`ticketFk` AS `ticketFk`,`t`.`shipped` AS `Fecha` from (((((((`vn`.`worker` `w` join `vn`.`itemType` `it` on((`it`.`workerFk` = `w`.`id`))) join `vn`.`item` `i` on((`i`.`typeFk` = `it`.`id`))) join `vn`.`sale` `s` on((`s`.`itemFk` = `i`.`id`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) left join `bi`.`Last_buy_id` `lb` on(((`lb`.`Id_Article` = `s`.`itemFk`) and (`lb`.`warehouse_id` = `t`.`warehouseFk`)))) left join `vn`.`buy` `b` on((`b`.`id` = `lb`.`Id_Compra`))) where ((`t`.`shipped` > '2018-01-01') and (`c`.`isRelevant` or (`c`.`id` in (200,400)))) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `workerMana` --- - -/*!50001 DROP VIEW IF EXISTS `workerMana`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerMana` AS select `m`.`Id_Trabajador` AS `workerFk`,`m`.`used` AS `amount` from `bs`.`mana_spellers` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Current Database: `cache` -- @@ -55179,10 +52972,10 @@ USE `vn`; /*!50001 SET collation_connection = @saved_col_connection */; -- --- Final view structure for view `clientManaCache` +-- Final view structure for view `clientManaCache__` -- -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!50001 DROP VIEW IF EXISTS `clientManaCache__`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; @@ -55191,7 +52984,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientManaCache` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; +/*!50001 VIEW `clientManaCache__` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -55263,7 +53056,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable` from `bi`.`tarifa_componentes` `t` */; +/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable`,`t`.`code` AS `code` from `bi`.`tarifa_componentes` `t` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -55996,9 +53789,9 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ /*!50001 VIEW `saleFreight` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`clientFk` AS `clientFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`zoneFk` AS `zoneFk`,`t`.`companyFk` AS `companyFk`,`t`.`shipped` AS `shipped`,`zc`.`price` AS `price`,((((`s`.`quantity` * `r`.`cm3`) * `zc`.`price`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume` from (((((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`packaging` `cb` on((`cb`.`id` = '94'))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) join `vn`.`zoneCalendar` `zc` on(((`zc`.`zoneFk` = `t`.`zoneFk`) and (`zc`.`delivered` = `t`.`landed`)))) */; @@ -56381,4 +54174,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-16 10:31:31 +-- Dump completed on 2019-12-23 14:34:48 diff --git a/db/export-structure.sh b/db/export-structure.sh index 1959463ff..5e1b62f03 100755 --- a/db/export-structure.sh +++ b/db/export-structure.sh @@ -3,7 +3,6 @@ SCHEMAS=( account bi - bs cache edi hedera diff --git a/docker-compose.yml b/docker-compose.yml index c0f02273e..c9011bdf4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,6 +10,8 @@ services: - ${PORT_FRONT}:80 links: - back + deploy: + replicas: 3 back: image: registry.verdnatura.es/salix-back:${TAG} restart: unless-stopped @@ -19,6 +21,8 @@ services: environment: - NODE_ENV volumes: - - /containers/salix:/etc/salix + - /mnt/storage/containers/salix:/etc/salix - /mnt/storage/pdfs:/var/lib/salix/pdfs - /mnt/storage/dms:/var/lib/salix/dms + deploy: + replicas: 6 diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 5b22ec6e2..ac2e215bd 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -48,11 +48,11 @@ export default { }, clientBasicData: { basicDataButton: 'vn-left-menu a[ui-sref="client.card.basicData"]', - nameInput: 'vn-client-basic-data [name="name"]', - contactInput: 'vn-client-basic-data [name="contact"]', phoneInput: 'vn-client-basic-data [name="phone"]', mobileInput: 'vn-client-basic-data [name="mobile"]', - emailInput: 'vn-client-basic-data [name="email"]', + nameInput: 'vn-textfield[ng-model="$ctrl.client.name"]', + contactInput: 'vn-textfield[ng-model="$ctrl.client.contact"]', + emailInput: 'vn-textfield[ng-model="$ctrl.client.email"]', salesPersonAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', channelAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.contactChannelFk"]', saveButton: `button[type=submit]` @@ -346,11 +346,11 @@ export default { acceptDeleteTurn: '.vn-confirm.shown button[response="accept"]' }, createTicketView: { - clientAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.clientFk"]', - addressAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.addressFk"]', + clientAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.clientId"]', + addressAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.addressId"]', deliveryDateInput: 'vn-ticket-create vn-date-picker[ng-model="$ctrl.landed"]', - warehouseAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.warehouseFk"]', - agencyAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.ticket.agencyModeFk"]', + warehouseAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.warehouseId"]', + agencyAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.agencyModeId"]', createButton: `button[type=submit]` }, ticketDescriptor: { @@ -359,7 +359,7 @@ export default { goBackToModuleIndexButton: 'vn-ticket-descriptor a[ui-sref="ticket.index"]', moreMenu: 'vn-ticket-descriptor vn-icon-menu[icon=more_vert]', moreMenuAddStowaway: '.vn-drop-down.shown li[name="Add stowaway"]', - moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Remove stowaway"]', + moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Delete stowaway"]', moreMenuAddToTurn: '.vn-drop-down.shown li[name="Add turn"]', moreMenuDeleteTicket: '.vn-drop-down.shown li[name="Delete ticket"]', moreMenuMakeInvoice: '.vn-drop-down.shown li[name="Make invoice"]', diff --git a/e2e/paths/02-client-module/02_edit_basic_data.spec.js b/e2e/paths/02-client-module/02_edit_basic_data.spec.js index 2cea50d35..59d58a7ae 100644 --- a/e2e/paths/02-client-module/02_edit_basic_data.spec.js +++ b/e2e/paths/02-client-module/02_edit_basic_data.spec.js @@ -14,159 +14,130 @@ describe('Client Edit basicData path', () => { page.close(); }); - // describe('as employee', () => { - it('should not be able to change the salesPerson', async() => { - // await page.wait(selectors.clientBasicData.nameInput); - // const result = await page.evaluate(selector => { - // return document.querySelector(selector).disabled; - // }, `${selectors.clientBasicData.salesPersonAutocomplete} input`); + describe('as employee', () => { + it('should not be able to change the salesPerson', async() => { + const result = await nightmare + .wait(selectors.clientBasicData.nameInput) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, `${selectors.clientBasicData.salesPersonAutocomplete} input`); - expect(result).toBeTruthy(); + expect(result).toBeTruthy(); + }); + + it('should edit the client basic data but leave salesPerson untainted', async() => { + const result = await nightmare + .clearInput(selectors.clientBasicData.nameInput) + .write(selectors.clientBasicData.nameInput, 'Ptonomy Wallace') + .clearInput(selectors.clientBasicData.contactInput) + .write(selectors.clientBasicData.contactInput, 'David Haller') + .clearInput(selectors.clientBasicData.emailInput) + .write(selectors.clientBasicData.emailInput, 'PWallace@verdnatura.es') + .autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Rumors on the streets') + .waitToClick(selectors.clientBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the name have been edited', async() => { + const result = await nightmare + .reloadSection('client.card.basicData') + .waitToGetProperty(selectors.clientBasicData.nameInput, 'value'); + + expect(result).toEqual('Ptonomy Wallace'); + }); + + it('should confirm the contact name have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.contactInput, 'value'); + + expect(result).toEqual('David Haller'); + }); + + it('should confirm the email have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); + + expect(result).toEqual('PWallace@verdnatura.es'); + }); + + it('should confirm the channel have been selected', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientBasicData.channelAutocomplete} input`, 'value'); + + expect(result).toEqual('Rumors on the streets'); + }); }); - // it('should edit the client basic data but leave salesPerson untainted', async() => { - // await page.clearInput(selectors.clientBasicData.nameInput); - // await page.write(selectors.clientBasicData.nameInput, 'Ptonomy Wallace'); - // await page.clearInput(selectors.clientBasicData.contactInput); - // await page.write(selectors.clientBasicData.contactInput, 'David Haller'); - // await page.clearInput(selectors.clientBasicData.phoneInput); - // await page.write(selectors.clientBasicData.phoneInput, '987654321'); - // await page.clearInput(selectors.clientBasicData.mobileInput); - // await page.write(selectors.clientBasicData.mobileInput, '123456789'); - // await page.clearInput(selectors.clientBasicData.emailInput); - // await page.write(selectors.clientBasicData.emailInput, 'PWallace@verdnatura.es'); - // await page.autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Rumors on the streets'); - // await page.waitToClick(selectors.clientBasicData.saveButton); - // const result = await page.waitForLastSnackbar(); + describe('as salesAssistant', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesASsistant', 'client') + .accessToSearchResult('Ptonomy Wallace') + .accessToSection('client.card.basicData'); + }); - // expect(result).toEqual('Data saved!'); - // }); + it('should be able to change the salesPerson', async() => { + const result = await nightmare + .wait(selectors.clientBasicData.nameInput) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, `${selectors.clientBasicData.salesPersonAutocomplete} input`); - // it('should confirm the name have been edited', async() => { - // await page.reloadSection('client.card.basicData'); - // const result = await page.waitToGetProperty(selectors.clientBasicData.nameInput, 'value'); + expect(result).toBeFalsy(); + }); - // expect(result).toEqual('Ptonomy Wallace'); - // }); + it('should edit the client basic data including salesPerson', async() => { + const result = await nightmare + .clearInput(selectors.clientBasicData.nameInput) + .write(selectors.clientBasicData.nameInput, 'Ororo Munroe') + .clearInput(selectors.clientBasicData.contactInput) + .write(selectors.clientBasicData.contactInput, 'Black Panther') + .clearInput(selectors.clientBasicData.emailInput) + .write(selectors.clientBasicData.emailInput, 'Storm@verdnatura.es') + .autocompleteSearch(selectors.clientBasicData.salesPersonAutocomplete, 'replenisherNick') + .autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Metropolis newspaper') + .waitToClick(selectors.clientBasicData.saveButton) + .waitForLastSnackbar(); - // it('should confirm the contact name have been edited', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.contactInput, 'value'); + expect(result).toEqual('Data saved!'); + }); - // expect(result).toEqual('David Haller'); - // }); + it('should now confirm the name have been edited', async() => { + const result = await nightmare + .reloadSection('client.card.basicData') + .waitToGetProperty(selectors.clientBasicData.nameInput, 'value'); - // it('should confirm the landline phone number have been added', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.phoneInput, 'value'); + expect(result).toEqual('Ororo Munroe'); + }); - // expect(result).toEqual('987654321'); - // }); + it('should now confirm the contact name have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.contactInput, 'value'); - // it('should confirm the mobile phone number have been added', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.mobileInput, 'value'); + expect(result).toEqual('Black Panther'); + }); - // expect(result).toEqual('123456789'); - // }); + it('should now confirm the email have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); - // it('should confirm the email have been edited', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); + expect(result).toEqual('Storm@verdnatura.es'); + }); - // expect(result).toEqual('PWallace@verdnatura.es'); - // }); + it('should confirm the sales person have been selected', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientBasicData.salesPersonAutocomplete} input`, 'value'); - // it('should confirm the channel have been selected', async() => { - // const result = await page - // .waitToGetProperty(`${selectors.clientBasicData.channelAutocomplete} input`, 'value'); + expect(result).toEqual('replenisherNick'); + }); - // expect(result).toEqual('Rumors on the streets'); - // }); - // }); + it('should now confirm the channel have been selected', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientBasicData.channelAutocomplete} input`, 'value'); - // describe('as salesAssistant', () => { - // beforeAll(async() => { - // await page.loginAndModule('salesASsistant', 'client'); - // await page.accessToSearchResult('Ptonomy Wallace'); - // await page.accessToSection('client.card.basicData'); - // }); - - // it('should be able to change the salesPerson', async() => { - // await page.wait(selectors.clientBasicData.nameInput); - // const result = await page.evaluate(selector => { - // return document.querySelector(selector).disabled; - // }, `${selectors.clientBasicData.salesPersonAutocomplete} input`); - - // expect(result).toBeFalsy(); - // }); - - // it('should edit the client basic data including salesPerson', async() => { - // await page.clearInput(selectors.clientBasicData.nameInput); - // await page.write(selectors.clientBasicData.nameInput, 'Ororo Munroe'); - // await page.clearInput(selectors.clientBasicData.contactInput); - // await page.write(selectors.clientBasicData.contactInput, 'Black Panther'); - // await page.clearInput(selectors.clientBasicData.phoneInput); - // await page.write(selectors.clientBasicData.phoneInput, '123456789'); - // await page.clearInput(selectors.clientBasicData.mobileInput); - // await page.write(selectors.clientBasicData.mobileInput, '987654321'); - // await page.clearInput(selectors.clientBasicData.emailInput); - // await page.write(selectors.clientBasicData.emailInput, 'Storm@verdnatura.es'); - // await page.autocompleteSearch(selectors.clientBasicData.salesPersonAutocomplete, 'replenisherNick'); - // await page.autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Metropolis newspaper'); - // await page.waitToClick(selectors.clientBasicData.saveButton); - // const result = await page.waitForLastSnackbar(); - - // expect(result).toEqual('Data saved!'); - // }); - - // it('should now confirm the name have been edited', async() => { - // await page.reloadSection('client.card.basicData'); - // const result = await page.waitToGetProperty(selectors.clientBasicData.nameInput, 'value'); - - // expect(result).toEqual('Ororo Munroe'); - // }); - - // it('should now confirm the contact name have been edited', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.contactInput, 'value'); - - // expect(result).toEqual('Black Panther'); - // }); - - // it('should now confirm the landline phone number have been added', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.phoneInput, 'value'); - - // expect(result).toEqual('123456789'); - // }); - - // it('should now confirm the mobile phone number have been added', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.mobileInput, 'value'); - - // expect(result).toEqual('987654321'); - // }); - - // it('should now confirm the email have been edited', async() => { - // const result = await page - // .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); - - // expect(result).toEqual('Storm@verdnatura.es'); - // }); - - // it('should confirm the sales person have been selected', async() => { - // const result = await page - // .waitToGetProperty(`${selectors.clientBasicData.salesPersonAutocomplete} input`, 'value'); - - // expect(result).toEqual('replenisherNick'); - // }); - - // it('should now confirm the channel have been selected', async() => { - // const result = await page - // .waitToGetProperty(`${selectors.clientBasicData.channelAutocomplete} input`, 'value'); - - // expect(result).toEqual('Metropolis newspaper'); - // }); - // }); + expect(result).toEqual('Metropolis newspaper'); + }); + }); }); diff --git a/front/core/components/autocomplete/index.js b/front/core/components/autocomplete/index.js index e2c9b7ad4..38c85db57 100755 --- a/front/core/components/autocomplete/index.js +++ b/front/core/components/autocomplete/index.js @@ -253,7 +253,7 @@ export default class Autocomplete extends Field { } showDropDown(search) { - if (this.readonly) return; + if (!this.editable) return; this.assignDropdownProps(); this.$.dropDown.show(this.container, search); } diff --git a/front/core/components/chip/style.scss b/front/core/components/chip/style.scss index 5840ecdf1..3778c62b9 100644 --- a/front/core/components/chip/style.scss +++ b/front/core/components/chip/style.scss @@ -14,8 +14,25 @@ vn-chip { &.colored { background-color: $color-main; - color: $color-font-dark; + color: $color-font-bg; } + &.notice { + background-color: $color-notice-medium + } + &.success { + background-color: $color-success-medium; + } + &.warning { + background-color: $color-main-medium; + } + &.alert { + background-color: $color-alert-medium; + } + &.message { + color: $color-font-dark; + background-color: $color-bg-dark + } + & > div { display: flex; align-items: center; diff --git a/front/core/components/range/index.js b/front/core/components/range/index.js index 80410875a..88463e7cf 100644 --- a/front/core/components/range/index.js +++ b/front/core/components/range/index.js @@ -6,6 +6,16 @@ export default class Range extends FormInput { constructor($element, $scope) { super($element, $scope); this.input = this.element.querySelector('input'); + this.input.addEventListener('change', () => this.onValueUpdate()); + } + + get field() { + return super.field; + } + + set field(value) { + this.input.value = value; + super.field = value; } get max() { @@ -35,6 +45,11 @@ export default class Range extends FormInput { refreshTabIndex() { this.input.tabIndex = this.disabled ? -1 : this.tabIndex; } + + onValueUpdate() { + this.change(this.input.value); + this.$.$applyAsync(); + } } ngModule.vnComponent('vnRange', { diff --git a/front/core/components/searchbar/searchbar.js b/front/core/components/searchbar/searchbar.js index 98f52ee36..a82324877 100644 --- a/front/core/components/searchbar/searchbar.js +++ b/front/core/components/searchbar/searchbar.js @@ -254,7 +254,6 @@ class AutoSearch { } } } - this.model.applyFilter( where ? {where} : null, hasParams ? userParams : null diff --git a/front/nginx.conf b/front/nginx.conf index 64f9436f3..22bce2283 100644 --- a/front/nginx.conf +++ b/front/nginx.conf @@ -7,11 +7,7 @@ server { client_max_body_size 250M; root /salix/dist; - error_page 404 = @notfound; - location @notfound { - return 302 /; - } location / { autoindex on; } diff --git a/gulpfile.js b/gulpfile.js index 2b77eb008..e8daac5b1 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -110,17 +110,27 @@ backTestOnce.description = `Runs the backend tests once, can receive --junit arg async function backTestDockerOnce() { let containerId = await docker(); - await backTestOnce(); - if (argv['random']) - await execP(`docker rm -fv ${containerId}`); + try { + await backTestOnce(); + } catch (e) { + throw e; + } finally { + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + } } backTestDockerOnce.description = `Runs backend tests using in site container once`; async function backTestDocker() { let containerId = await docker(); - await backTest(); - if (argv['random']) - await execP(`docker rm -fv ${containerId}`); + try { + await backTest(); + } catch (e) { + throw e; + } finally { + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + } } backTestDocker.description = `Runs backend tests restoring fixtures first`; diff --git a/modules/agency/front/location/style.scss b/modules/agency/front/location/style.scss index 4972a5d29..2316a2622 100644 --- a/modules/agency/front/location/style.scss +++ b/modules/agency/front/location/style.scss @@ -1,14 +1,19 @@ @import "variables"; vn-treeview-child { - .content > .vn-check:not(.indeterminate) { - color: $color-button; + .content > .vn-check:not(.indeterminate):not(.checked) { + color: $color-alert; & > .btn { - border-color: $color-button; + border-color: $color-alert; } } .content > .vn-check.checked { - color: $color-button; + color: $color-notice; + + & > .btn { + background-color: $color-notice; + border-color: $color-notice + } } } \ No newline at end of file diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index 136016b1e..e1e95728b 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -18,7 +18,6 @@ module.exports = Self => { }); Self.regularizeClaim = async(ctx, params) => { - const userId = ctx.req.accessToken.userId; const models = Self.app.models; const resolvedState = 3; @@ -55,11 +54,10 @@ module.exports = Self => { if (!ticketFk) { ticketFk = await createTicket(ctx, { - clientFk: address.clientFk, - addressFk: addressFk, - warehouseFk: sale.ticket().warehouseFk, - companyFk: sale.ticket().companyFk, - userId: userId + clientId: address.clientFk, + warehouseId: sale.ticket().warehouseFk, + companyId: sale.ticket().companyFk, + addressId: addressFk }, options); } @@ -140,16 +138,21 @@ module.exports = Self => { } async function createTicket(ctx, params, options) { - let ticket = await Self.app.models.Ticket.new(ctx, - { - shipped: new Date(), - landed: new Date(), - clientFk: params.clientFk, - warehouseFk: params.warehouseFk, - companyFk: params.companyFk, - addressFk: params.addressFk, - userId: params.userId - }, options); + params.shipped = new Date(); + params.landed = new Date(); + params.agencyModeId = null; + params.routeId = null; + + const ticket = await Self.app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyId, + params.addressId, + params.agencyModeId, + params.routeId, + options); return ticket.id; } diff --git a/modules/claim/front/action/index.js b/modules/claim/front/action/index.js index 7d67d58c9..23e69bbe9 100644 --- a/modules/claim/front/action/index.js +++ b/modules/claim/front/action/index.js @@ -2,12 +2,13 @@ import ngModule from '../module'; import './style.scss'; class Controller { - constructor($stateParams, $scope, $http, $translate, vnApp) { + constructor($stateParams, $scope, $http, $translate, vnApp, $httpParamSerializer) { this.$stateParams = $stateParams; this.$ = $scope; this.$http = $http; this.$translate = $translate; this.vnApp = vnApp; + this.$httpParamSerializer = $httpParamSerializer; this.filter = { where: {claimFk: $stateParams.id}, include: [ @@ -125,31 +126,61 @@ class Controller { let data = {claimFk: this.$stateParams.id}; let query = `Claims/regularizeClaim`; return this.$http.post(query, data).then(() => { - this.card.reload(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); if (this.claim.responsibility >= Math.ceil(this.maxResponsibility) / 2) this.$.updateGreuge.show(); + else + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + + this.card.reload(); }); } + getGreugeTypeId() { + const params = {filter: {where: {code: 'freightPickUp'}}}; + const serializedParams = this.$httpParamSerializer(params); + const query = `GreugeTypes/findOne?${serializedParams}`; + return this.$http.get(query).then(res => { + this.greugeTypeFreightId = res.data.id; + + return res; + }); + } + + getGreugeConfig() { + const query = `GreugeConfigs/findOne`; + return this.$http.get(query).then(res => { + this.freightPickUpPrice = res.data.freightPickUpPrice; + + return res; + }); + } + + onUpdateGreugeResponse(response) { - if (response !== 'accept') - return; - let greugeTypeFreight = 7; - let query = `Greuges/`; - let data = { - clientFk: this.claim.clientFk, - description: `claim: ${this.claim.id}`, - amount: 11, - greugeTypeFk: greugeTypeFreight, - ticketFk: this.claim.ticketFk - }; + if (response == 'accept') { + const promises = []; + promises.push(this.getGreugeTypeId()); + promises.push(this.getGreugeConfig()); - this.$http.post(query, data).then(() => { - this.card.reload(); - this.vnApp.showSuccess(this.$translate.instant('Greuge inserted!')); - }); + return Promise.all(promises).then(() => { + const data = { + clientFk: this.claim.clientFk, + description: this.$translate.instant('ClaimGreugeDescription', { + claimId: this.claim.id + }).toUpperCase(), + amount: this.freightPickUpPrice, + greugeTypeFk: this.greugeTypeFreightId, + ticketFk: this.claim.ticketFk + }; + return this.$http.post(`Greuges/`, data).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showMessage(this.$translate.instant('Greuge inserted')); + }); + }); + } else + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); } + // Item Descriptor showDescriptor(event, itemFk) { this.$.descriptor.itemFk = itemFk; @@ -164,6 +195,7 @@ class Controller { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); }); } + saveMana(value) { let query = `Claims/${this.$stateParams.id}/updateClaimAction`; @@ -173,7 +205,7 @@ class Controller { } } -Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp']; +Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp', '$httpParamSerializer']; ngModule.component('vnClaimAction', { template: require('./index.html'), diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index 56597fd2f..0d10957e7 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -6,15 +6,19 @@ describe('claim', () => { let controller; let $httpBackend; let $state; + let $httpParamSerializer; + let $scope; beforeEach(ngModule('claim')); - beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { + beforeEach(angular.mock.inject(($rootScope, $componentController, _$state_, _$httpBackend_, _$httpParamSerializer_) => { + $scope = $rootScope.$new(); $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; $state = _$state_; $state.params.id = 1; - controller = $componentController('vnClaimAction', {$state}); + controller = $componentController('vnClaimAction', {$state, $scope}); controller.claim = {ticketFk: 1}; controller.$.model = {refresh: () => {}}; controller.$.addSales = { @@ -149,6 +153,8 @@ describe('claim', () => { }); describe('onUpdateGreugeResponse()', () => { + const greugeTypeId = 7; + const freightPickUpPrice = 11; it('should do nothing', () => { spyOn(controller.$http, 'post'); spyOn(controller.card, 'reload'); @@ -161,24 +167,51 @@ describe('claim', () => { expect(controller.vnApp.showSuccess).not.toHaveBeenCalledWith('Greuge inserted!'); }); - it('should perform a insert into greuges', () => { + it('should make a query and get the greugeTypeId and greuge config', () => { spyOn(controller.card, 'reload'); spyOn(controller.vnApp, 'showSuccess'); + + const greugeTypeParams = $httpParamSerializer({filter: {where: {code: 'freightPickUp'}}}); + $httpBackend.expect('GET', `GreugeTypes/findOne?${greugeTypeParams}`).respond({id: greugeTypeId}); + $httpBackend.expect('GET', `GreugeConfigs/findOne`).respond({freightPickUpPrice}); + controller.onUpdateGreugeResponse('accept'); + $httpBackend.flush(); + + expect(controller.greugeTypeFreightId).toEqual(greugeTypeId); + expect(controller.freightPickUpPrice).toEqual(freightPickUpPrice); + }); + + // #1957 - Investigate how to test nested httpBackend requests + xit('should perform a insert into greuges', () => { + spyOn(controller.card, 'reload'); + spyOn(controller.vnApp, 'showSuccess'); + + spyOn(controller, 'getGreugeTypeId').and.returnValue(new Promise(resolve => { + return resolve({id: greugeTypeId}); + })); + spyOn(controller, 'getGreugeConfig').and.returnValue(new Promise(resolve => { + return resolve({freightPickUpPrice}); + })); + controller.claim.clientFk = 101; controller.claim.id = 11; let data = { clientFk: 101, description: `claim: ${controller.claim.id}`, - amount: 11, - greugeTypeFk: 7, + amount: freightPickUpPrice, + greugeTypeFk: greugeTypeId, ticketFk: controller.claim.ticketFk }; - $httpBackend.expect('POST', `Greuges/`, data).respond(); - controller.onUpdateGreugeResponse('accept'); - $httpBackend.flush(); + $httpBackend.expect('POST', `Greuges/`, data).respond(new Promise(resolve => { + return resolve({id: freightPickUpPrice}); + })); + controller.onUpdateGreugeResponse('accept').then(res => { + console.log('asdas'); + }).catch(error => { + console.log('errorrrr!!'); + }); - expect(controller.card.reload).toHaveBeenCalledWith(); - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Greuge inserted!'); + $httpBackend.flush(); }); }); }); diff --git a/modules/claim/front/action/locale/en.yml b/modules/claim/front/action/locale/en.yml new file mode 100644 index 000000000..faab67c06 --- /dev/null +++ b/modules/claim/front/action/locale/en.yml @@ -0,0 +1 @@ +ClaimGreugeDescription: Claim id {{claimId}} \ No newline at end of file diff --git a/modules/claim/front/action/locale/es.yml b/modules/claim/front/action/locale/es.yml index 3950ec06a..db1a25755 100644 --- a/modules/claim/front/action/locale/es.yml +++ b/modules/claim/front/action/locale/es.yml @@ -8,4 +8,5 @@ Imports ticket lines: Importa las lineas de un ticket Regularize: Regularizar Do you want to insert greuges?: Desea insertar greuges? Insert greuges on client card: Insertar greuges en la ficha del cliente -Greuge inserted: Greuge insertado \ No newline at end of file +Greuge inserted: Greuge insertado +ClaimGreugeDescription: Reclamación id {{claimId}} \ No newline at end of file diff --git a/modules/claim/front/dms/index/index.html b/modules/claim/front/dms/index/index.html index e3cd5da5b..bd6b9a21d 100644 --- a/modules/claim/front/dms/index/index.html +++ b/modules/claim/front/dms/index/index.html @@ -11,7 +11,7 @@ + class="vn-w-xl">
+ class="vn-w-lg"> diff --git a/modules/claim/front/locale/es.yml b/modules/claim/front/locale/es.yml index f636b43ee..26b1eba32 100644 --- a/modules/claim/front/locale/es.yml +++ b/modules/claim/front/locale/es.yml @@ -7,7 +7,7 @@ Claimed ticket: Ticket reclamado Delete claim: Eliminar reclamación Observation: Observación Responsible: Responsable -Remove sale: Borrar linea +Remove sale: Eliminar linea Claim Id: Id reclamación Created: Creado Send Pickup order: Enviar orden de recogida diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html index c5d954057..20dca702b 100644 --- a/modules/claim/front/summary/index.html +++ b/modules/claim/front/summary/index.html @@ -87,7 +87,7 @@
+ zoom-image="/api/dms/{{::photo.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}">
diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 6c69d32a8..e3b0edf8a 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -60,6 +60,8 @@ module.exports = function(Self) { scope: { fields: ['id', 'name', 'active'] } + }, { + relation: 'phones' } ] }); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 155d95d9e..13e898f09 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -53,6 +53,9 @@ module.exports = Self => { } } }, + { + relation: 'phones' + }, { relation: 'country', scope: { diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index 3aa709eb7..670b7d2ca 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -50,6 +50,9 @@ "GreugeType": { "dataSource": "vn" }, + "GreugeConfig": { + "dataSource": "vn" + }, "Mandate": { "dataSource": "vn" }, diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index c62ae3832..4529b3caf 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -200,6 +200,11 @@ "type": "hasOne", "model": "ClaimRatio", "foreignKey": "clientFk" - } + }, + "phones": { + "type": "hasMany", + "model": "UserPhone", + "foreignKey": "userFk" + } } } \ No newline at end of file diff --git a/modules/client/back/models/greuge-config.json b/modules/client/back/models/greuge-config.json new file mode 100644 index 000000000..b72348023 --- /dev/null +++ b/modules/client/back/models/greuge-config.json @@ -0,0 +1,20 @@ +{ + "name": "GreugeConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "greugeConfig" + } + }, + "properties": { + "freightPickUpPrice": { + "type": "Number" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} diff --git a/modules/client/back/models/greuge-type.json b/modules/client/back/models/greuge-type.json index cafe1f7fc..5c5b1870d 100644 --- a/modules/client/back/models/greuge-type.json +++ b/modules/client/back/models/greuge-type.json @@ -2,19 +2,22 @@ "name": "GreugeType", "base": "VnModel", "options": { - "mysql": { - "table": "greugeType" - } + "mysql": { + "table": "greugeType" + } }, "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "name": { - "type": "String" - } + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "code": { + "type": "String" + } }, "acls": [ { diff --git a/modules/client/front/basic-data/index.html b/modules/client/front/basic-data/index.html index 8c00f7a18..fbf883d98 100644 --- a/modules/client/front/basic-data/index.html +++ b/modules/client/front/basic-data/index.html @@ -31,20 +31,6 @@ info="You can save multiple emails"> - - - - - - { - this.$scope.watcher.notifySaved(); - this.$scope.model.refresh(); - }); - } -} - -Controller.$inject = ['$scope', '$stateParams', '$translate']; - -ngModule.component('vnClientContact', { - template: require('./index.html'), - controller: Controller, - bindings: { - client: '<' - } -}); diff --git a/modules/client/front/dms/index/index.html b/modules/client/front/dms/index/index.html index e45821a4a..9ecafe887 100644 --- a/modules/client/front/dms/index/index.html +++ b/modules/client/front/dms/index/index.html @@ -61,7 +61,8 @@ {{::document.dms.file}} + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> + {{::document.dms.file}} @@ -74,7 +75,7 @@ + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> diff --git a/modules/client/front/greuge/index/index.html b/modules/client/front/greuge/index/index.html index 636caaca2..683ac0afe 100644 --- a/modules/client/front/greuge/index/index.html +++ b/modules/client/front/greuge/index/index.html @@ -37,7 +37,9 @@ {{::greuge.shipped | date:'dd/MM/yyyy HH:mm' }} - {{::greuge.description}} + + {{::greuge.description}} + {{::greuge.greugeType.name}} {{::greuge.amount | currency: 'EUR': 2}} diff --git a/modules/client/front/index.js b/modules/client/front/index.js index 324046206..514319ee2 100644 --- a/modules/client/front/index.js +++ b/modules/client/front/index.js @@ -30,7 +30,7 @@ import './credit-insurance/index'; import './credit-insurance/create'; import './credit-insurance/insurance/index'; import './credit-insurance/insurance/create'; -import './contact'; +import './phones'; import './sample/index'; import './sample/create'; import './web-payment'; diff --git a/modules/client/front/index/index.html b/modules/client/front/index/index.html index 35a5234aa..184f18727 100644 --- a/modules/client/front/index/index.html +++ b/modules/client/front/index/index.html @@ -25,10 +25,6 @@ label="Id" value="{{::client.id}}"> - - diff --git a/modules/client/front/index/index.js b/modules/client/front/index/index.js index 56ab594ff..51dd41dea 100644 --- a/modules/client/front/index/index.js +++ b/modules/client/front/index/index.js @@ -24,10 +24,11 @@ export default class Controller { case 'socialName': case 'city': return {[param]: {like: `%${value}%`}}; + case 'email': + return {[param]: {like: `%${value}%`}}; case 'id': case 'fi': case 'postcode': - case 'email': case 'salesPersonFk': return {[param]: value}; } diff --git a/modules/client/front/locale/es.yml b/modules/client/front/locale/es.yml index baca4d479..1b44b5652 100644 --- a/modules/client/front/locale/es.yml +++ b/modules/client/front/locale/es.yml @@ -18,7 +18,7 @@ Sent: Enviado Worker: Trabajador Sample: Plantilla Credit: Crédito -Are you sure you want to delete this expedition?: ¿Está seguro de borrar esta expedición? +Are you sure you want to delete this expedition?: ¿Está seguro de eliminar esta expedición? Others: Otros New order: Nuevo pedido Client frozen: Cliente congelado diff --git a/modules/client/front/contact/index.html b/modules/client/front/phones/index.html similarity index 51% rename from modules/client/front/contact/index.html rename to modules/client/front/phones/index.html index 2cefdd86d..c0966ce0f 100644 --- a/modules/client/front/contact/index.html +++ b/modules/client/front/phones/index.html @@ -1,45 +1,48 @@ + + + url="UserPhones" + data="$ctrl.phones"> + data="$ctrl.phones">
- - - + + + + ng-model="clientPhone.phone"> + ng-click="model.remove($index)" + tabindex="-1"> @@ -48,4 +51,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/phones/index.js b/modules/client/front/phones/index.js new file mode 100644 index 000000000..9839d27d7 --- /dev/null +++ b/modules/client/front/phones/index.js @@ -0,0 +1,44 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +class Controller extends Section { + get client() { + return this._client; + } + + set client(value) { + this._client = value; + if (value) + this.setLink(value); + } + + setLink(value) { + this.$.$applyAsync(()=> { + this.$.model.link = {userFk: value.id}; + this.$.model.refresh(); + }); + } + + onSubmit() { + this.$.watcher.check(); + return this.$.model.save().then(() => { + this.$.watcher.updateOriginalData(); + this.$.watcher.notifySaved(); + this.card.reload(); + }); + } + + add() { + this.$.model.insert(); + } +} + + +ngModule.component('vnClientPhones', { + template: require('./index.html'), + controller: Controller, + require: {card: '^vnClientCard'}, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/phones/index.spec.js b/modules/client/front/phones/index.spec.js new file mode 100644 index 000000000..3d0befd68 --- /dev/null +++ b/modules/client/front/phones/index.spec.js @@ -0,0 +1,50 @@ +import './index'; +import watcher from 'core/mocks/watcher'; + +describe('Component vnClientPhones', () => { + let controller; + let $element; + let $scope; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $element = angular.element('
'); + $scope.watcher = watcher; + $scope.model = { + link: 1, + save: () => {} + }; + controller = $componentController('vnClientPhones', {$element, $scope}); + controller.card = {reload: () => {}}; + })); + + describe('setLink()', () => { + it('set the link in the model and refreshes it', () => { + spyOn(controller.$, '$applyAsync'); + let value = {id: 106}; + controller.setLink(value); + + expect(controller.$.$applyAsync).toHaveBeenCalledWith(jasmine.any(Function)); + }); + }); + + describe('onSubmit()', () => { + it('should call watcher functions, reload the card and save the model', done => { + spyOn(controller.$.watcher, 'check'); + spyOn(controller.$.model, 'save').and.returnValue(Promise.resolve()); + + spyOn(controller.$.watcher, 'updateOriginalData'); + spyOn(controller.$.watcher, 'notifySaved'); + spyOn(controller.card, 'reload'); + controller.onSubmit(); + controller.onSubmit().then(() => { + expect(controller.$.watcher.updateOriginalData).toHaveBeenCalledWith(); + expect(controller.$.watcher.notifySaved).toHaveBeenCalledWith(); + expect(controller.card.reload).toHaveBeenCalledWith(); + done(); + }).catch(done.fail); + }); + }); +}); diff --git a/modules/client/front/routes.json b/modules/client/front/routes.json index ef0d8cc7a..6d96bd284 100644 --- a/modules/client/front/routes.json +++ b/modules/client/front/routes.json @@ -26,7 +26,7 @@ {"state": "client.card.webAccess", "icon": "cloud"}, {"state": "client.card.mandate", "icon": "pan_tool"}, {"state": "client.card.creditInsurance.index", "icon": "icon-solunion"}, - {"state": "client.card.contact", "icon": "contact_phone"}, + {"state": "client.card.phones", "icon": "contact_phone"}, {"state": "client.card.sample.index", "icon": "mail"}, {"state": "client.card.webPayment", "icon": "icon-onlinepayment"}, {"state": "client.card.dms.index", "icon": "cloud_upload"} @@ -282,10 +282,10 @@ "client": "$ctrl.client" } }, { - "url": "/contact", - "state": "client.card.contact", - "component": "vn-client-contact", - "description": "Contacts", + "url": "/phones", + "state": "client.card.phones", + "component": "vn-client-phones", + "description": "Client phones", "params": { "client": "$ctrl.client" } diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index eccf45873..7016a19ff 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -12,11 +12,9 @@ - - - + diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 345e29125..fece307de 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -2,13 +2,16 @@ const app = require('vn-loopback/server/server'); describe('invoiceOut book()', () => { const invoiceOutId = 1; - let invoiceOutRef; + let bookedDate; let OriginalInvoiceOut; let updatedInvoiceOut; - let bookedDate; afterAll(async done => { - updatedInvoiceOut.updateAttributes({booked: OriginalInvoiceOut.booked, hasPdf: OriginalInvoiceOut.hasPdf}); + updatedInvoiceOut.updateAttributes({ + booked: OriginalInvoiceOut.booked, + hasPdf: OriginalInvoiceOut.hasPdf, + amount: OriginalInvoiceOut.amount + }); done(); }); @@ -24,7 +27,7 @@ describe('invoiceOut book()', () => { it(`should confirm the book property have been updated`, async() => { OriginalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - invoiceOutRef = OriginalInvoiceOut.ref; + let invoiceOutRef = OriginalInvoiceOut.ref; await app.models.InvoiceOut.book(invoiceOutRef); diff --git a/modules/invoiceOut/front/descriptor/locale/es.yml b/modules/invoiceOut/front/descriptor/locale/es.yml index 4f6abcea3..e85be96bf 100644 --- a/modules/invoiceOut/front/descriptor/locale/es.yml +++ b/modules/invoiceOut/front/descriptor/locale/es.yml @@ -3,7 +3,7 @@ Volume: Volumen Client card: Ficha del cliente Invoice ticket list: Listado de tickets de la factura Show invoice PDF: Ver factura en PDF -Delete Invoice: Borrar factura +Delete Invoice: Eliminar factura InvoiceOut deleted: Factura eliminada Are you sure you want to delete this invoice?: Estas seguro de eliminar esta factura? Book invoice: Asentar factura diff --git a/modules/item/back/methods/item/regularize.js b/modules/item/back/methods/item/regularize.js index b9c646086..a532b0083 100644 --- a/modules/item/back/methods/item/regularize.js +++ b/modules/item/back/methods/item/regularize.js @@ -29,7 +29,6 @@ module.exports = Self => { }); Self.regularize = async(ctx, itemFk, quantity, warehouseFk) => { - const userId = ctx.req.accessToken.userId; const models = Self.app.models; const itemDestination = await models.ClaimDestination.findOne({ @@ -56,10 +55,9 @@ module.exports = Self => { if (!ticketFk) { ticketFk = await createTicket(ctx, { - clientFk: itemDestination.address().clientFk, - addressFk: itemDestination.addressFk, - warehouseFk: warehouseFk, - userId: userId + clientId: itemDestination.address().clientFk, + warehouseId: warehouseFk, + addressId: itemDestination.addressFk }, options); } @@ -88,17 +86,22 @@ module.exports = Self => { } async function createTicket(ctx, params, options) { - let ticket = await Self.app.models.Ticket.new( - ctx, - { - shipped: new Date(), - landed: new Date(), - clientFk: params.clientFk, - warehouseFk: params.warehouseFk, - companyFk: params.companyFk, - addressFk: params.addressFk, - userId: params.userId - }, options); + params.shipped = new Date(); + params.landed = new Date(); + params.companyId = null; + params.agencyModeId = null; + params.routeId = null; + + const ticket = await Self.app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyId, + params.addressId, + params.agencyModeId, + params.routeId, + options); return ticket.id; } diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index 4fe9bfe21..bd0cec86d 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -31,7 +31,15 @@ show-field="name" value-field="id" ng-model="$ctrl.item.typeFk" - initial-data="$ctrl.item.itemType"> + initial-data="$ctrl.item.itemType" + fields="['categoryFk']" + include="'category'"> + +
{{name}}
+
+ {{category.name}} +
+
diff --git a/modules/item/front/botanical/index.html b/modules/item/front/botanical/index.html index 8353841b3..b6d836b30 100644 --- a/modules/item/front/botanical/index.html +++ b/modules/item/front/botanical/index.html @@ -29,14 +29,21 @@ value-field="genus_id" label="Genus"> - + fields="['genus_id']" + include="'genus'"> + +
{{latin_species_name}}
+
+ {{genus.latin_genus_name}} +
+
diff --git a/modules/item/front/create/index.html b/modules/item/front/create/index.html index 0c00aa8e9..e57da198c 100644 --- a/modules/item/front/create/index.html +++ b/modules/item/front/create/index.html @@ -19,13 +19,19 @@ - -
{{::code}}
-
{{::name}}
+ search-function="{or: [{code: {like: $search +'%'}}, {name: {like: '%'+ $search +'%'}}]}" + include="'category'"> + +
+
{{::code}}
+
{{::name}}
+
+
+ {{category.name}} +
- + - {{entry.warehouse| dashIfEmpty}} - {{entry.landed | date:'dd/MM/yyyy HH:mm'}} - {{entry.entryFk | dashIfEmpty}} - {{entry.price2 | dashIfEmpty}} - {{entry.price3 | dashIfEmpty}} + {{::entry.warehouse| dashIfEmpty}} + {{::entry.landed | date:'dd/MM/yyyy HH:mm'}} + {{::entry.entryFk | dashIfEmpty}} + {{::entry.price2 | dashIfEmpty}} + {{::entry.price3 | dashIfEmpty}} {{entry.stickers | dashIfEmpty}} - - {{entry.packing | dashIfEmpty}} - + + {{::entry.packing | dashIfEmpty}} + - - {{entry.grouping | dashIfEmpty}} - + + {{::entry.grouping | dashIfEmpty}} + - {{entry.stems | dashIfEmpty}} - {{entry.quantity}} - {{entry.buyingValue | dashIfEmpty}} - {{entry.packageFk | dashIfEmpty}} - {{entry.supplier | dashIfEmpty}} + {{::entry.stems | dashIfEmpty}} + {{::entry.quantity}} + {{::entry.buyingValue | dashIfEmpty}} + {{::entry.packageFk | dashIfEmpty}} + {{::entry.supplier | dashIfEmpty}} diff --git a/modules/item/front/search-panel/index.html b/modules/item/front/search-panel/index.html index ea0d854f5..f30442ec6 100644 --- a/modules/item/front/search-panel/index.html +++ b/modules/item/front/search-panel/index.html @@ -20,14 +20,21 @@ value-field="id" ng-model="filter.categoryFk"> - + ng-model="filter.typeFk" + fields="['categoryFk']" + include="'category'"> + +
{{name}}
+
+ {{category.name}} +
+
>
diff --git a/modules/order/back/methods/order/getItemTypeAvailable.js b/modules/order/back/methods/order/getItemTypeAvailable.js index 977a2cf85..de0a5511c 100644 --- a/modules/order/back/methods/order/getItemTypeAvailable.js +++ b/modules/order/back/methods/order/getItemTypeAvailable.js @@ -38,11 +38,12 @@ module.exports = Self => { order.agencyModeFk ]); stmts.push(stmt); - stmt = new ParameterizedSQL(`SELECT it.id, it.name + stmt = new ParameterizedSQL(`SELECT it.id, it.name, ic.name categoryName FROM tmp.availableCalc ac JOIN cache.available a ON a.calc_id = ac.calcFk JOIN item i ON i.id = a.item_id JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk WHERE it.categoryFk = ? GROUP BY it.id`, [ itemCategoryId diff --git a/modules/order/front/descriptor/locale/es.yml b/modules/order/front/descriptor/locale/es.yml index 21f3051ca..0734d7638 100644 --- a/modules/order/front/descriptor/locale/es.yml +++ b/modules/order/front/descriptor/locale/es.yml @@ -7,6 +7,6 @@ Items: Articulos Agency: Agencia Sales person: Comercial Order ticket list: Ticket del pedido -Delete order: Borrar pedido -You are going to delete this order: El pedido se borrará +Delete order: Eliminar pedido +You are going to delete this order: El pedido se eliminará continue anyway?: ¿Continuar de todos modos? \ No newline at end of file diff --git a/modules/order/front/filter/index.html b/modules/order/front/filter/index.html index 68691e0a7..2b92b5f4a 100644 --- a/modules/order/front/filter/index.html +++ b/modules/order/front/filter/index.html @@ -29,7 +29,15 @@ ng-model="$ctrl.type.id" show-field="name" value-field="id" - label="Type"> + label="Type" + fields="['categoryFk']" + include="'category'"> + +
{{name}}
+
+ {{categoryName}} +
+
diff --git a/modules/order/front/line/locale/es.yml b/modules/order/front/line/locale/es.yml index 688778561..d1368d369 100644 --- a/modules/order/front/line/locale/es.yml +++ b/modules/order/front/line/locale/es.yml @@ -1,3 +1,3 @@ Delete row: Eliminar linea Order confirmed: Pedido confirmado -Are you sure you want to delete this row?: ¿Estas seguro de que quieres borrar esta línea? \ No newline at end of file +Are you sure you want to delete this row?: ¿Estas seguro de que quieres eliminar esta línea? \ No newline at end of file diff --git a/modules/route/front/tickets/locale/es.yml b/modules/route/front/tickets/locale/es.yml index 7edeff17b..02f9eed08 100644 --- a/modules/route/front/tickets/locale/es.yml +++ b/modules/route/front/tickets/locale/es.yml @@ -1,8 +1,8 @@ -Remove ticket: Borrar ticket +Remove ticket: Eliminar ticket Open buscaman: Abrir buscaman -Ticket removed from route: Ticket borrado de la ruta +Ticket removed from route: Ticket quitado de la ruta Order changed: Orden cambiado -Delete ticket from route?: ¿Borrar ticket de la ruta? +Delete ticket from route?: ¿Quitar el ticket de la ruta? Sort routes: Ordenar rutas Add ticket: Añadir ticket Tickets to add: Tickets a añadir \ No newline at end of file diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 37930f1b3..2a751697f 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -8,8 +8,8 @@ describe('sale updatePrice()', () => { let manaComponentId; beforeAll(async done => { - let componentRate = await app.models.ComponentRate.findOne({where: {code: 'mana'}}); - manaComponentId = componentRate.id; + let component = await app.models.Component.findOne({where: {code: 'mana'}}); + manaComponentId = component.id; originalSale = await app.models.Sale.findById(saleId); originalSalesPersonMana = await app.models.WorkerMana.findById(18); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 60a171e17..75e226c42 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -59,7 +59,7 @@ module.exports = Self => { let usesMana = await models.WorkerMana.findOne({where: {workerFk: salesPerson}, fields: 'amount'}, options); let componentCode = usesMana ? 'mana' : 'buyerDiscount'; - let discount = await models.ComponentRate.findOne({where: {code: componentCode}}, options); + let discount = await models.Component.findOne({where: {code: componentCode}}, options); let componentId = discount.id; let componentValue = newPrice - sale.price; diff --git a/modules/ticket/back/methods/ticket/canHaveStowaway.js b/modules/ticket/back/methods/ticket/canHaveStowaway.js index 0d64c2d11..bbc6cf4b3 100644 --- a/modules/ticket/back/methods/ticket/canHaveStowaway.js +++ b/modules/ticket/back/methods/ticket/canHaveStowaway.js @@ -21,10 +21,17 @@ module.exports = Self => { Self.canHaveStowaway = async id => { const models = Self.app.models; - const ticket = await models.Ticket.findById(id); + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'ship', + scope: { + fields: ['id'] + } + } + }); const warehouse = await models.Warehouse.findById(ticket.warehouseFk); - - if (warehouse && warehouse.hasStowaway) + const hasStowaway = ticket.ship() ? true : false; + if (warehouse && warehouse.hasStowaway && !hasStowaway) return true; return false; diff --git a/modules/ticket/back/methods/ticket/deleteStowaway.js b/modules/ticket/back/methods/ticket/deleteStowaway.js new file mode 100644 index 000000000..6f3a1760f --- /dev/null +++ b/modules/ticket/back/methods/ticket/deleteStowaway.js @@ -0,0 +1,39 @@ + +module.exports = Self => { + Self.remoteMethod('deleteStowaway', { + description: 'Deletes an stowaway', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/deleteStowaway`, + verb: 'POST' + } + }); + + Self.deleteStowaway = async id => { + const ticket = await Self.findById(id, { + include: [{ + relation: 'ship' + }, { + relation: 'stowaway' + }] + }); + + let params; + if (ticket.stowaway()) + params = [ticket.stowaway().shipFk, ticket.stowaway().id]; + else if (ticket.ship()) + params = [ticket.ship().shipFk, ticket.ship().id]; + + return Self.rawSql(`CALL vn.stowaway_unboarding(?, ?)`, params); + }; +}; diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index 25e5a08c5..db5310f7c 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -2,14 +2,50 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('new', { - description: 'Create a newticket and returns the new ID', + description: 'Creates a new ticket and returns the id', accessType: 'WRITE', accepts: [{ - arg: 'params', - type: 'object', - required: true, - description: 'ClientFk, Shipped, WarehouseFk, CompanyFk, AddressFk, AgencyModeFk, RouteFk, Landed, userId', - http: {source: 'body'} + arg: 'clientId', + type: 'Number', + description: `The client id filter`, + required: true + }, + { + arg: 'shipped', + type: 'Date', + description: `The shipment date filter` + }, + { + arg: 'landed', + type: 'Date', + description: `The landing date filter` + }, + { + arg: 'warehouseId', + type: 'Number', + description: `The warehouse id filter`, + required: true + }, + { + arg: 'companyId', + type: 'Number', + description: `The company id filter` + }, + { + arg: 'addressId', + type: 'Number', + description: `The address id filter`, + required: true + }, + { + arg: 'agencyModeId', + type: 'Number', + description: `The agencyMode id filter` + }, + { + arg: 'routeId', + type: 'Number', + description: `The route id filter` }], returns: { type: 'number', @@ -21,28 +57,29 @@ module.exports = Self => { } }); - Self.new = async(ctx, params, options) => { - let models = Self.app.models; - let address = await models.Address.findOne({ - where: {id: params.addressFk}, + Self.new = async(ctx, clientId, shipped, landed, warehouseId, + companyId, addressId, agencyModeId, routeId, options) => { + const myUserId = ctx.req.accessToken.userId; + const models = Self.app.models; + const address = await models.Address.findOne({ + where: {id: addressId}, fields: ['id', 'clientFk'], - include: [ - {relation: 'client', - scope: { - include: { - relation: 'type' - } + include: { + relation: 'client', + scope: { + include: { + relation: 'type' } } - ] + } }); if (!address) throw new UserError(`This address doesn't exist`); let agencyMode; - if (params && params.agencyModeFk) - agencyMode = await models.AgencyMode.findById(params.agencyModeFk); + if (agencyModeId) + agencyMode = await models.AgencyMode.findById(agencyModeId); if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { if (!address.client().isActive) @@ -60,33 +97,30 @@ module.exports = Self => { } try { - if (!params.shipped && params.landed) { - const shippedResult = await models.Agency.getShipped(params.landed, - address.id, params.agencyModeFk, params.warehouseFk); - params.shipped = shippedResult && shippedResult.shipped; + if (!shipped && landed) { + const shippedResult = await models.Agency.getShipped(landed, + address.id, agencyModeId, warehouseId); + shipped = shippedResult && shippedResult.shipped; } - if (params.shipped && !params.landed) { - const landedResult = await models.Agency.getLanded(params.shipped, - address.id, params.agencyModeFk, params.warehouseFk); - params.landed = landedResult && landedResult.landed; + if (shipped && !landed) { + const landedResult = await models.Agency.getLanded(shipped, + address.id, agencyModeId, warehouseId); + landed = landedResult && landedResult.landed; } - if (!params.userId && ctx.req && ctx.req.accessToken.userId) - params.userId = ctx.req.accessToken.userId; - query = `CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result); SELECT @result newTicketId;`; let result = await Self.rawSql(query, [ - params.clientFk, - params.shipped, - params.warehouseFk, - params.companyFk || 442, - params.addressFk, - params.agencyModeFk || null, - params.routeFk || null, - params.landed, - params.userId + clientId, + shipped, + warehouseId, + companyId || 442, + addressId, + agencyModeId || null, + routeId || null, + landed, + myUserId ], options); let ticket = await models.Ticket.findById(result[1][0].newTicketId, null, options); @@ -94,7 +128,7 @@ module.exports = Self => { let logRecord = { originFk: cleanInstance.id, - userFk: params.userId, + userFk: myUserId, action: 'create', changedModel: 'Ticket', changedModelId: cleanInstance.id, diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index 25ce90946..04570390d 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -13,7 +13,7 @@ describe('ticket componentUpdate()', () => { let componentOfSaleEight; beforeAll(async done => { - let deliveryComponenet = await app.models.ComponentRate.findOne({where: {code: 'delivery'}}); + let deliveryComponenet = await app.models.Component.findOne({where: {code: 'delivery'}}); deliveryComponentId = deliveryComponenet.id; componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js new file mode 100644 index 000000000..3c8097e37 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket deleteStowaway()', () => { + const shipId = 16; + const stowawayId = 17; + + it('should create an stowaway', async() => { + await app.models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId]); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(1); + }); + + it('should delete the stowaway from the ship ticket', async() => { + await app.models.Ticket.deleteStowaway(shipId); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(0); + }); + + it('should create again an stowaway', async() => { + await app.models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId]); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(1); + }); + + it('should delete the stowaway from the stowaway ticket', async() => { + await app.models.Ticket.deleteStowaway(stowawayId); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(0); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js index 80147c2f2..87bc89b12 100644 --- a/modules/ticket/back/methods/ticket/specs/new.spec.js +++ b/modules/ticket/back/methods/ticket/specs/new.spec.js @@ -15,42 +15,74 @@ describe('ticket new()', () => { it('should throw an error if the client isnt frozen and isnt active', async() => { let error; - let params = {addressFk: 6}; + let params = { + clientId: 106, + shipped: today, + landed: null, + warehouseId: 1, + companyId: 442, + addressId: 6 + }; - await app.models.Ticket.new(ctx, params) - .catch(e => { - error = e; - }); + await app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyFk, + params.addressId + ).catch(e => { + error = e; + }); expect(error).toEqual(new UserError(`You can't create a ticket for a inactive client`)); }); it('should throw an error if the address doesnt exist', async() => { let error; - let params = {addressFk: 'invalid address', clientFk: 104}; + let params = { + clientId: 104, + shipped: today, + landed: null, + warehouseId: 1, + companyId: 442, + addressId: 'invalid address' + }; - await app.models.Ticket.new(ctx, params) - .catch(response => { - expect(response.message).toEqual(`This address doesn't exist`); - error = response; - }); + await app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyFk, + params.addressId + ).catch(response => { + expect(response.message).toEqual(`This address doesn't exist`); + error = response; + }); expect(error).toBeDefined(); }); it('should return the id of the created ticket', async() => { let params = { - warehouseFk: 1, - clientFk: 104, - companyFk: 442, - addressFk: 4, - agencyModeFk: 1, - userId: 9, + clientId: 104, shipped: today, - landed: today + landed: today, + warehouseId: 1, + companyId: 442, + addressId: 4, + agencyModeId: 1 }; - ticket = await app.models.Ticket.new(ctx, params); + ticket = await app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyFk, + params.addressId, + params.agencyModeId); let newestTicketIdInFixtures = 21; diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 75de1f538..111897efe 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -8,7 +8,7 @@ describe('sale updateDiscount()', () => { beforeAll(async done => { originalSale = await app.models.Sale.findById(originalSaleId); - let manaDiscount = await app.models.ComponentRate.findOne({where: {code: 'mana'}}); + let manaDiscount = await app.models.Component.findOne({where: {code: 'mana'}}); componentId = manaDiscount.id; let ticket = await app.models.Ticket.findById(originalSale.ticketFk); diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 94ada046f..66b4d6f95 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -88,7 +88,7 @@ module.exports = Self => { fields: 'amount'}, options); const componentCode = usesMana ? 'mana' : 'buyerDiscount'; - const discountComponent = await models.ComponentRate.findOne({ + const discountComponent = await models.Component.findOne({ where: {code: componentCode}}, options); const componentId = discountComponent.id; diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 3b38f1a16..10c10b134 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -5,10 +5,10 @@ "AnnualAverageInvoiced": { "dataSource": "vn" }, - "ComponentRate": { + "Component": { "dataSource": "vn" }, - "ComponentTypeRate": { + "ComponentType": { "dataSource": "vn" }, "Expedition": { diff --git a/modules/ticket/back/models/component-type-rate.json b/modules/ticket/back/models/component-type.json similarity index 92% rename from modules/ticket/back/models/component-type-rate.json rename to modules/ticket/back/models/component-type.json index c9b80f45c..ced725309 100644 --- a/modules/ticket/back/models/component-type-rate.json +++ b/modules/ticket/back/models/component-type.json @@ -1,5 +1,5 @@ { - "name": "ComponentTypeRate", + "name": "ComponentType", "base": "VnModel", "options": { "mysql": { diff --git a/modules/ticket/back/models/component-rate.json b/modules/ticket/back/models/component.json similarity index 92% rename from modules/ticket/back/models/component-rate.json rename to modules/ticket/back/models/component.json index 535b6086f..002b4804f 100644 --- a/modules/ticket/back/models/component-rate.json +++ b/modules/ticket/back/models/component.json @@ -1,5 +1,5 @@ { - "name": "ComponentRate", + "name": "Component", "base": "VnModel", "options": { "mysql": { @@ -34,7 +34,7 @@ "relations": { "componentType": { "type": "belongsTo", - "model": "ComponentTypeRate", + "model": "ComponentType", "foreignKey": "typeFk" } }, diff --git a/modules/ticket/back/models/sale-component.json b/modules/ticket/back/models/sale-component.json index 49edab2ae..3b7991fbb 100644 --- a/modules/ticket/back/models/sale-component.json +++ b/modules/ticket/back/models/sale-component.json @@ -25,9 +25,9 @@ "model": "Sale", "foreignKey": "saleFk" }, - "componentRate": { + "component": { "type": "belongsTo", - "model": "ComponentRate", + "model": "Component", "foreignKey": "componentFk" } } diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index c42df62ef..8ba2bfb0d 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -27,6 +27,7 @@ module.exports = Self => { require('../methods/ticket/transferSales')(Self); require('../methods/ticket/canHaveStowaway')(Self); require('../methods/ticket/recalculateComponents')(Self); + require('../methods/ticket/deleteStowaway')(Self); Self.observe('before save', async function(ctx) { if (ctx.isNewInstance) return; diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index 7b6c4a64b..113e6a75f 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -51,7 +51,7 @@ "foreignKey": "clientFk" }, "ship": { - "type": "hasMany", + "type": "hasOne", "model": "Stowaway", "foreignKey": "shipFk" }, diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html index 2a70baa9d..16db43a2e 100644 --- a/modules/ticket/front/component/index.html +++ b/modules/ticket/front/component/index.html @@ -45,19 +45,19 @@ - {{::component.componentRate.componentType.type}} + {{::saleComponent.component.componentType.type}} - {{::component.componentRate.name}} + {{::saleComponent.component.name}} - {{::component.value | currency: 'EUR':3}} + {{::saleComponent.value | currency: 'EUR':3}} - {{::sale.quantity * component.value | currency: 'EUR':3}} + {{::sale.quantity * saleComponent.value | currency: 'EUR':3}} diff --git a/modules/ticket/front/component/index.js b/modules/ticket/front/component/index.js index 9854305f6..027fdad77 100644 --- a/modules/ticket/front/component/index.js +++ b/modules/ticket/front/component/index.js @@ -15,7 +15,7 @@ class Controller { scope: { fields: ['componentFk', 'value'], include: { - relation: 'componentRate', + relation: 'component', scope: { fields: ['typeFk', 'name'], include: { @@ -38,9 +38,9 @@ class Controller { if (!sales) return; for (let sale of sales) { - for (let component of sale.components) { - if (component.componentRate.componentType.isBase) - sum += sale.quantity * component.value; + for (let saleComponent of sale.components) { + if (saleComponent.component.componentType.isBase) + sum += sale.quantity * saleComponent.value; } } diff --git a/modules/ticket/front/component/index.spec.js b/modules/ticket/front/component/index.spec.js index e75bf2bdb..4dd361b27 100644 --- a/modules/ticket/front/component/index.spec.js +++ b/modules/ticket/front/component/index.spec.js @@ -14,7 +14,7 @@ describe('ticket', () => { $scope.model.data = [{ components: [ { - componentRate: { + component: { name: 'valor de compra', componentType: { isBase: 1 @@ -23,7 +23,7 @@ describe('ticket', () => { value: 5 }, { - componentRate: { + component: { name: 'reparto', componentType: { isBase: 0 @@ -32,7 +32,7 @@ describe('ticket', () => { value: 5 }, { - componentRate: { + component: { name: 'recobro', componentType: { isBase: 0 @@ -46,7 +46,7 @@ describe('ticket', () => { { components: [ { - componentRate: { + component: { name: 'valor de compra', componentType: { isBase: 1 @@ -55,7 +55,7 @@ describe('ticket', () => { value: 1 }, { - componentRate: { + component: { name: 'reparto', componentType: { isBase: 0 @@ -64,7 +64,7 @@ describe('ticket', () => { value: 1 }, { - componentRate: { + component: { name: 'recobro', componentType: { isBase: 0 diff --git a/modules/ticket/front/create/card.html b/modules/ticket/front/create/card.html index cd26f21e7..6e6b5de62 100644 --- a/modules/ticket/front/create/card.html +++ b/modules/ticket/front/create/card.html @@ -1,20 +1,19 @@ - {{id}}: {{name}} @@ -25,18 +24,18 @@ ng-model="$ctrl.landed"> + ng-model="$ctrl.agencyModeId"> \ No newline at end of file diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js index 629647416..2e775c18b 100644 --- a/modules/ticket/front/create/card.js +++ b/modules/ticket/front/create/card.js @@ -14,9 +14,13 @@ class Controller { $onInit() { if (this.$stateParams && this.$stateParams.clientFk) - this.clientFk = this.$stateParams.clientFk; + this.clientId = this.$stateParams.clientFk; - this.warehouseFk = this.vnConfig.warehouseFk; + this.warehouseId = this.vnConfig.warehouseFk; + } + + get ticket() { + return this._ticket; } set ticket(value) { @@ -24,11 +28,11 @@ class Controller { this._ticket = value; } - get ticket() { - return this._ticket; + get clientId() { + return this.ticket.clientFk; } - set clientFk(value) { + set clientId(value) { this.ticket.clientFk = value; if (value) { @@ -36,7 +40,7 @@ class Controller { include: { relation: 'defaultAddress', scope: { - fields: 'id' + fields: ['id', 'agencyModeFk'] } }, where: {id: value} @@ -44,32 +48,21 @@ class Controller { filter = encodeURIComponent(JSON.stringify(filter)); let query = `Clients?filter=${filter}`; this.$http.get(query).then(res => { - if (res.data) { - let client = res.data[0]; - let defaultAddress = client.defaultAddress; - this.addressFk = defaultAddress.id; - } + const [client] = res.data; + this.defaultAddress = client.defaultAddress; + this.addressId = this.defaultAddress.id; }); } else - this.addressFk = null; + this.addressId = null; this.getAvailableAgencies(); } - get clientFk() { - return this.ticket.clientFk; - } - - set addressFk(value) { - this.ticket.addressFk = value; - this.getAvailableAgencies(); - } - - get addressFk() { + get addressId() { return this.ticket.addressFk; } - set landed(value) { - this.ticket.landed = value; + set addressId(value) { + this.ticket.addressFk = value; this.getAvailableAgencies(); } @@ -77,12 +70,26 @@ class Controller { return this.ticket.landed; } - set warehouseFk(value) { + set landed(value) { + this.ticket.landed = value; + this.getAvailableAgencies(); + } + + get warehouseId() { + return this.ticket.warehouseFk; + } + + set warehouseId(value) { this.ticket.warehouseFk = value; this.getAvailableAgencies(); } - get warehouseFk() { - return this.ticket.warehouseFk; + + get agencyModeId() { + return this.ticket.agencyModeFk; + } + + set agencyModeId(value) { + this.ticket.agencyModeFk = value; } getAvailableAgencies() { @@ -96,8 +103,11 @@ class Controller { if (params.warehouseFk && params.addressFk && params.landed) { ticket.agencyModeFk = null; - this.$http.get(`Agencies/getAgenciesWithWarehouse`, {params}) - .then(res => this._availableAgencies = res.data); + this.$http.get(`Agencies/getAgenciesWithWarehouse`, {params}).then(res => { + this._availableAgencies = res.data; + + this.agencyModeId = this.defaultAddress.agencyModeFk; + }); } } @@ -107,11 +117,11 @@ class Controller { createTicket() { let params = { - clientFk: this.ticket.clientFk, + clientId: this.ticket.clientFk, landed: this.ticket.landed, - addressFk: this.ticket.addressFk, - agencyModeFk: this.ticket.agencyModeFk, - warehouseFk: this.ticket.warehouseFk, + addressId: this.ticket.addressFk, + agencyModeId: this.ticket.agencyModeFk, + warehouseId: this.ticket.warehouseFk, }; this.$http.post(`Tickets/new`, params).then(res => { this.vnApp.showSuccess(this.translate.instant('Data saved!')); diff --git a/modules/ticket/front/descriptor/addStowaway.html b/modules/ticket/front/descriptor/addStowaway.html index 4ffab8ce5..ec7005e79 100644 --- a/modules/ticket/front/descriptor/addStowaway.html +++ b/modules/ticket/front/descriptor/addStowaway.html @@ -7,10 +7,10 @@ class="modal-form" on-open="model.refresh()"> -
+
Stowaways to add
- + diff --git a/modules/ticket/front/descriptor/index.html b/modules/ticket/front/descriptor/index.html index decc0b6d4..3632d37f1 100644 --- a/modules/ticket/front/descriptor/index.html +++ b/modules/ticket/front/descriptor/index.html @@ -139,11 +139,12 @@ card-reload="$ctrl.cardReload()" ticket="$ctrl.ticket"> - - + + this.canShowStowaway }, { - name: 'Remove stowaway', - callback: this.showRemoveStowaway, - show: () => this.shouldShowRemoveStowaway() + name: 'Delete stowaway', + callback: this.showDeleteStowaway, + show: () => this.shouldShowDeleteStowaway() }, { name: 'Make invoice', @@ -43,6 +43,54 @@ class Controller extends Component { ]; } + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (!value) return; + + if (this.$params.sendSMS) + this.showSMSDialog(); + + this.canStowaway(); + + let links = { + btnOne: { + icon: 'person', + state: `client.card.summary({id: ${value.clientFk}})`, + tooltip: 'Client card' + }}; + + if (value.stowaway) { + links.btnTwo = { + icon: 'icon-stowaway', + state: `ticket.card.summary({id: ${value.stowaway.shipFk}})`, + tooltip: 'Ship stowaways' + }; + } + + if (value.ship) { + links.btnThree = { + icon: 'icon-stowaway', + state: `ticket.card.summary({id: ${value.ship.id}})`, + tooltip: 'Stowaway' + }; + } + + this._quicklinks = links; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + showChangeShipped() { if (!this.isEditable) { this.vnApp.showError(this.$translate.instant(`This ticket can't be modified`)); @@ -72,24 +120,6 @@ class Controller extends Component { return false; } - canStowaway() { - if (!this.isTicketModule()) return; - - this.$http.get(`Tickets/${this.ticket.id}/canHaveStowaway`).then(response => { - if (response.data === true) - return this.canShowStowaway = true; - - return this.canShowStowaway = false; - }); - } - - shouldShowRemoveStowaway() { - if (!this._ticket || !this.isTicketModule()) - return false; - - return (this._ticket.stowaway || (this._ticket.ship && this._ticket.ship.length > 0)); - } - onMoreChange(callback) { callback.call(this); } @@ -149,61 +179,38 @@ class Controller extends Component { } } + canStowaway() { + if (!this.isTicketModule()) return; + + this.$http.get(`Tickets/${this.ticket.id}/canHaveStowaway`).then(response => { + if (response.data === true) + return this.canShowStowaway = true; + + return this.canShowStowaway = false; + }); + } + + shouldShowDeleteStowaway() { + if (!this._ticket || !this.isTicketModule()) + return false; + + return this._ticket.stowaway || this._ticket.ship; + } + showAddStowaway() { this.$.addStowaway.show(); } - showRemoveStowaway() { - this.$.removeStowaway.show(); + showDeleteStowaway() { + this.$.deleteStowaway.show(); } - get ticket() { - return this._ticket; - } - - set ticket(value) { - this._ticket = value; - - if (!value) return; - - if (this.$params.sendSMS) - this.showSMSDialog(); - - this.canStowaway(); - - let links = { - btnOne: { - icon: 'person', - state: `client.card.summary({id: ${value.clientFk}})`, - tooltip: 'Client card' - }}; - - if (value.stowaway) { - links.btnTwo = { - icon: 'icon-stowaway', - state: `ticket.card.summary({id: ${value.stowaway.shipFk}})`, - tooltip: 'Ship stowaways' - }; - } - - if (value.ship && value.ship.length == 1) { - links.btnThree = { - icon: 'icon-stowaway', - state: `ticket.card.summary({id: ${value.ship[0].id}})`, - tooltip: 'Stowaway' - }; - } else if (value.ship && value.ship.length > 1) - this.shipStowaways = value.ship; - - this._quicklinks = links; - } - - set quicklinks(value = {}) { - this._quicklinks = Object.assign(value, this._quicklinks); - } - - get quicklinks() { - return this._quicklinks; + deleteStowaway() { + const query = `Tickets/${this.ticket.id}/deleteStowaway`; + this.$http.post(query).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.cardReload(); + }); } showDeliveryNote() { diff --git a/modules/ticket/front/descriptor/index.spec.js b/modules/ticket/front/descriptor/index.spec.js index 937a837b3..eb554218e 100644 --- a/modules/ticket/front/descriptor/index.spec.js +++ b/modules/ticket/front/descriptor/index.spec.js @@ -174,11 +174,11 @@ describe('Ticket Component vnTicketDescriptor', () => { describe('showRemoveStowaway()', () => { it('should show a dialog for an stowaway removal', () => { - controller.$.removeStowaway = {}; - controller.$.removeStowaway.show = jasmine.createSpy('show'); - controller.showRemoveStowaway(); + controller.$.deleteStowaway = {}; + controller.$.deleteStowaway.show = jasmine.createSpy('show'); + controller.showDeleteStowaway(); - expect(controller.$.removeStowaway.show).toHaveBeenCalledWith(); + expect(controller.$.deleteStowaway.show).toHaveBeenCalledWith(); }); }); diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index 2f72e226e..947377e19 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -5,8 +5,8 @@ Ship stowaways: Polizones del barco Stowaways to add: Polizones a añadir Stowaways of the ticket: Polizones del ticket Add stowaway: Añadir polizón -Remove stowaway: Borrar polizón -Are you sure you want to delete this stowaway?: ¿Seguro que quieres borrar este polizón? +Delete stowaway: Eliminar polizón +Are you sure you want to delete this stowaway?: ¿Seguro que quieres eliminar este polizón? Are you sure you want to send it?: ¿Seguro que quieres enviarlo? Show Delivery Note: Ver albarán Send Delivery Note: Enviar albarán diff --git a/modules/ticket/front/descriptor/removeStowaway.html b/modules/ticket/front/descriptor/removeStowaway.html deleted file mode 100644 index 891329b7e..000000000 --- a/modules/ticket/front/descriptor/removeStowaway.html +++ /dev/null @@ -1,38 +0,0 @@ - - - -
Stowaways of the ticket {{$ctrl.ticket.id}}
-
- - - - - Ticket id - Shipped - Agency - Warehouse - State - - - - - {{stowaway.id}} - {{stowaway.ticket.landed | date: 'dd/MM/yyyy'}} - {{stowaway.ticket.agencyMode.name}} - {{stowaway.ticket.warehouse.name}} - {{stowaway.ticket.state.state.name}} - - - - -
-
- - - \ No newline at end of file diff --git a/modules/ticket/front/descriptor/removeStowaway.js b/modules/ticket/front/descriptor/removeStowaway.js deleted file mode 100644 index 05ace7d9e..000000000 --- a/modules/ticket/front/descriptor/removeStowaway.js +++ /dev/null @@ -1,78 +0,0 @@ -import ngModule from '../module'; - -class Controller { - constructor($state, $scope, $http, vnApp, $translate) { - this.vnApp = vnApp; - this.$translate = $translate; - this.$scope = $scope; - this.$state = $state; - this.$http = $http; - } - - getTicketStowaways() { - if (this.ticket.stowaway) { - this.ticketStowaways = [this.ticket.stowaway]; - this.showDeleteConfirm(0); - } else if (this.ticket.ship.length > 1) { - let filter = { - where: {shipFk: this.ticket.id}, - include: { - relation: 'ticket', - scope: { - include: [ - {relation: 'agencyMode'}, - {relation: 'warehouse'}, - {relation: 'state', - scope: { - fields: ['stateFk'], - include: { - relation: 'state' - } - }, - }, - ] - } - } - }; - - let json = encodeURIComponent(JSON.stringify(filter)); - this.$http.get(`Stowaways?filter=${json}`).then(res => { - this.ticketStowaways = res.data; - this.$scope.dialog.show(); - }); - } - } - - deleteStowaway(response) { - if (response === 'accept') { - this.$http.delete(`Stowaways/${this.stowawayToDelete.id}`).then(res => { - this.cardReload(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - }); - } - } - - showDeleteConfirm(index) { - this.stowawayToDelete = this.ticketStowaways[index]; - this.$scope.confirmationDialog.show(); - } - - show() { - this.getTicketStowaways(); - } - - hide() { - this.$scope.dialog.hide(); - } -} - -Controller.$inject = ['$state', '$scope', '$http', 'vnApp', '$translate']; - -ngModule.component('vnRemoveStowaway', { - template: require('./removeStowaway.html'), - controller: Controller, - bindings: { - ticket: '<', - cardReload: '&?' - } -}); diff --git a/modules/ticket/front/descriptor/style.scss b/modules/ticket/front/descriptor/style.scss index e0abcbc50..4becf9789 100644 --- a/modules/ticket/front/descriptor/style.scss +++ b/modules/ticket/front/descriptor/style.scss @@ -1,6 +1,6 @@ @import "variables"; -vn-add-stowaway { +.add-stowaway { vn-data-viewer { width: 40em } diff --git a/modules/ticket/front/dms/index/index.html b/modules/ticket/front/dms/index/index.html index 278427338..ae2844c73 100644 --- a/modules/ticket/front/dms/index/index.html +++ b/modules/ticket/front/dms/index/index.html @@ -59,7 +59,7 @@
+ href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> {{::document.dms.file}} @@ -73,7 +73,7 @@ + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> diff --git a/modules/ticket/front/index.js b/modules/ticket/front/index.js index f8433b5fe..58ee9136e 100644 --- a/modules/ticket/front/index.js +++ b/modules/ticket/front/index.js @@ -6,7 +6,6 @@ import './search-panel'; import './card'; import './descriptor'; import './descriptor/addStowaway'; -import './descriptor/removeStowaway'; import './descriptor-popover'; import './create/card'; import './create/index'; diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml index 2b7f75c0c..b26a6d6fa 100644 --- a/modules/ticket/front/locale/es.yml +++ b/modules/ticket/front/locale/es.yml @@ -14,8 +14,8 @@ Counter: Contador Created : Añadido Date : Fecha Delay: Retraso -Delete: Borrar -Delete expedition: Borrar expedición +Delete: Eliminar +Delete expedition: Eliminar expedición Description: Descripción Discount: Descuento Employee : Empleado @@ -42,7 +42,7 @@ PPU: Ud. Price: Precio Price gap: Diferencia de precio Quantity: Cantidad -Remove lines: Borrar lineas +Remove lines: Eliminar lineas Route: Ruta SET OK: PONER OK Shipment: Salida diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index 7113732e1..d0854c996 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -11,28 +11,25 @@ class Controller { this.$http = $http; this.edit = {}; this.moreOptions = [ - {name: 'Send SMS', callback: this.showSMSDialog}, { + name: 'Send SMS', + callback: this.showSMSDialog + }, { name: 'Mark as reserved', callback: this.markAsReserved, show: () => this.isEditable - }, - { + }, { name: 'Unmark as reserved', callback: this.unmarkAsReserved, show: () => this.isEditable - }, - { + }, { name: 'Update discount', callback: this.showEditDialog, show: () => this.isEditable - }, - { + }, { name: 'Add claim', - callback: this.createClaim, - show: () => this.isEditable - }, - { + callback: this.createClaim + }, { name: 'Recalculate price', callback: this.calculateSalePrice, show: () => this.hasOneSaleSelected() diff --git a/modules/ticket/front/sale/locale/es.yml b/modules/ticket/front/sale/locale/es.yml index f381eb6e6..3ccdd528e 100644 --- a/modules/ticket/front/sale/locale/es.yml +++ b/modules/ticket/front/sale/locale/es.yml @@ -1,7 +1,7 @@ New price: Nuevo precio Add item: Añadir artículo Add turn: Añadir a turno -Delete ticket: Borrar ticket +Delete ticket: Eliminar ticket Mark as reserved: Marcar como reservado Unmark as reserved: Desmarcar como reservado Update discount: Actualizar descuento @@ -10,7 +10,7 @@ Edit discount: Editar descuento Transfer to ticket: Transferir a ticket New ticket: Nuevo ticket Edit price: Editar precio -You are going to delete lines of the ticket: Vas a borrar lineas del ticket +You are going to delete lines of the ticket: Vas a eliminar lineas del ticket This ticket will be removed from current route! Continue anyway?: ¡Se eliminará el ticket de la ruta actual! ¿Continuar de todas formas? You have to allow pop-ups in your web browser to use this functionality: Debes permitir los pop-pups en tu navegador para que esta herramienta funcione correctamente @@ -29,5 +29,5 @@ SMSAvailability: >- {{notAvailables}} no disponible/s. Disculpe las molestias. Continue anyway?: ¿Continuar de todas formas? This ticket is now empty: El ticket ha quedado vacio -Do you want to delete it?: ¿Quieres borrarlo? +Do you want to delete it?: ¿Quieres eliminarlo? Recalculate price: Recalcular precio \ No newline at end of file diff --git a/modules/travel/back/methods/travel/filter.js b/modules/travel/back/methods/travel/filter.js new file mode 100644 index 000000000..ecf152b0c --- /dev/null +++ b/modules/travel/back/methods/travel/filter.js @@ -0,0 +1,141 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: 'Searchs the travel by id', + http: {source: 'query'} + }, { + arg: 'id', + type: 'Integer', + description: 'The travel id', + http: {source: 'query'} + }, { + arg: 'shippedFrom', + type: 'Date', + description: 'The shipped from date filter', + http: {source: 'query'} + }, { + arg: 'shippedTo', + type: 'Date', + description: 'The shipped to date filter', + http: {source: 'query'} + }, { + arg: 'landedFrom', + type: 'Date', + description: 'The landed from date filter', + http: {source: 'query'} + }, { + arg: 'landedTo', + type: 'Date', + description: 'The landed to date filter', + http: {source: 'query'} + }, { + arg: 'agencyFk', + type: 'Number', + description: 'The agencyModeFk id', + http: {source: 'query'} + }, { + arg: 'warehouseOutFk', + type: 'Number', + description: 'The warehouseOutFk filter', + http: {source: 'query'} + }, { + arg: 'warehouseInFk', + type: 'Number', + description: 'The warehouseInFk filter', + http: {source: 'query'} + }, { + arg: 'totalEntries', + type: 'Number', + description: 'The totalEntries filter', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return {'t.id': value}; + case 'ref': + return {[param]: {regexp: value}}; + case 'shippedFrom': + return {'t.shipped': {gte: value}}; + case 'shippedTo': + return {'t.shipped': {lte: value}}; + case 'landedFrom': + return {'t.landed': {gte: value}}; + case 'landedTo': + return {'t.landed': {lte: value}}; + case 'id': + case 'agencyFk': + case 'warehouseOutFk': + case 'warehouseInFk': + case 'totalEntries': + param = `t.${param}`; + return {[param]: value}; + } + }); + + filter = mergeFilters(ctx.args.filter, {where}); + + let stmts = []; + let stmt; + stmt = new ParameterizedSQL( + `SELECT + t.id, + t.shipped, + t.landed, + t.warehouseInFk, + t.warehouseOutFk, + t.agencyFk, + t.ref, + t.isDelivered, + t.isReceived, + t.m3, + t.kg, + t.cargoSupplierFk, + t.totalEntries, + am.name agencyModeName, + win.name warehouseInName, + wout.name warehouseOutName + FROM vn.travel t + JOIN vn.agencyMode am ON am.id = t.agencyFk + JOIN vn.warehouse win ON win.id = t.warehouseInFk + JOIN vn.warehouse wout ON wout.id = t.warehouseOutFk` + ); + + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; + diff --git a/modules/travel/back/methods/travel/specs/filter.spec.js b/modules/travel/back/methods/travel/specs/filter.spec.js new file mode 100644 index 000000000..f2fe44989 --- /dev/null +++ b/modules/travel/back/methods/travel/specs/filter.spec.js @@ -0,0 +1,58 @@ +const app = require('vn-loopback/server/server'); + +describe('Travel filter()', () => { + it('should return the travel matching "search"', async() => { + let ctx = { + args: { + search: 1 + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + }); + + it('should return the travel matching "warehouse out"', async() => { + let ctx = { + args: { + warehouseOutFk: 2 + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(7); + }); + + it('should return the travel matching "total entries"', async() => { + let ctx = { + args: { + totalEntries: 1, + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(5); + }); + + it('should return the routes matching "shipped from" and "shipped to"', async() => { + const from = new Date(); + const to = new Date(); + from.setHours(0, 0, 0, 0); + to.setHours(23, 59, 59, 999); + to.setDate(to.getDate() + 1); + let ctx = { + args: { + shippedFrom: from, + shippedTo: to + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(1); + }); +}); diff --git a/modules/travel/back/models/travel.js b/modules/travel/back/models/travel.js index 936b68cd9..5fa55a366 100644 --- a/modules/travel/back/models/travel.js +++ b/modules/travel/back/models/travel.js @@ -1,4 +1,5 @@ module.exports = Self => { require('../methods/travel/getTravel')(Self); require('../methods/travel/getEntries')(Self); + require('../methods/travel/filter')(Self); }; diff --git a/modules/travel/front/index/index.html b/modules/travel/front/index/index.html index 044f1ca8f..3af99eb6b 100644 --- a/modules/travel/front/index/index.html +++ b/modules/travel/front/index/index.html @@ -1,17 +1,17 @@ + params="::$ctrl.params" + data="travels" + order="shipped DESC, landed DESC"> + on-search="$ctrl.onSearch($params)"> + class="vn-mb-xl vn-w-xl"> @@ -34,11 +34,11 @@ ui-sref="travel.card.summary({id: {{::travel.id}}})"> {{::travel.id}} {{::travel.ref}} - {{::travel.agency.name}} - {{::travel.warehouseOut.name}} + {{::travel.agencyModeName}} + {{::travel.warehouseOutName}} {{::travel.shipped | date:'dd/MM/yyyy'}} - {{::travel.warehouseIn.name}} + {{::travel.warehouseInName}} {{::travel.landed | date:'dd/MM/yyyy'}} @@ -51,8 +51,8 @@ - + diff --git a/modules/travel/front/index/index.js b/modules/travel/front/index/index.js index a4dd60d77..a1e22d2e7 100644 --- a/modules/travel/front/index/index.js +++ b/modules/travel/front/index/index.js @@ -4,44 +4,6 @@ export default class Controller { constructor($scope) { this.$ = $scope; this.ticketSelected = null; - - this.filter = { - include: [ - { - relation: 'agency', - scope: {fields: ['name']} - }, { - relation: 'warehouseIn', - scope: {fields: ['name']} - }, { - relation: 'warehouseOut', - scope: {fields: ['name']} - } - ] - }; - } - - exprBuilder(param, value) { - switch (param) { - case 'search': - return {id: value}; - case 'ref': - return {[param]: {regexp: value}}; - case 'shippedFrom': - return {shipped: {gte: value}}; - case 'shippedTo': - return {shipped: {lte: value}}; - case 'landedFrom': - return {landed: {gte: value}}; - case 'landedTo': - return {landed: {lte: value}}; - case 'id': - case 'agencyModeFk': - case 'warehouseOutFk': - case 'warehouseInFk': - case 'totalEntries': - return {[param]: value}; - } } preview(event, travel) { @@ -50,6 +12,29 @@ export default class Controller { event.preventDefault(); event.stopImmediatePropagation(); } + + getScopeDates(days) { + const today = new Date(); + today.setHours(0, 0, 0, 0); + const daysOnward = new Date(today); + daysOnward.setDate(today.getDate() + days); + daysOnward.setHours(23, 59, 59, 999); + return {shippedFrom: today, shippedTo: daysOnward}; + } + + onSearch(params) { + if (params) { + let newParams = params; + if (params.scopeDays) { + const scopeDates = this.getScopeDates(params.scopeDays); + Object.assign(newParams, scopeDates); + } else if (Object.entries(params).length == 0) + newParams = this.getScopeDates(1); + + this.$.model.applyFilter(null, newParams); + } else + this.$.model.clear(); + } } Controller.$inject = ['$scope']; diff --git a/modules/travel/front/index/index.spec.js b/modules/travel/front/index/index.spec.js index 321109003..5affc7c1a 100644 --- a/modules/travel/front/index/index.spec.js +++ b/modules/travel/front/index/index.spec.js @@ -3,31 +3,62 @@ import './index.js'; describe('Travel Component vnTravelIndex', () => { let $componentController; let controller; + let $window; + let travels = [{ + id: 1, + warehouseInFk: 1, + totalEntries: 3, + isDelivered: false + }, { + id: 2, + warehouseInFk: 1, + total: 4, + isDelivered: true + }, { + id: 3, + warehouseInFk: 1, + total: 2, + isDelivered: true + }]; beforeEach(angular.mock.module('travel', $translateProvider => { $translateProvider.translations('en', {}); })); - beforeEach(angular.mock.inject(_$componentController_ => { + beforeEach(angular.mock.inject((_$componentController_, $rootScope) => { $componentController = _$componentController_; - controller = $componentController('vnTravelIndex'); + let $scope = $rootScope.$new(); + controller = $componentController('vnTravelIndex', $scope); + controller.$.summary = {show: jasmine.createSpy('show')}; })); - describe('exprBuilder()', () => { - it('should return a formated object with the travel id in case of search', () => { - let param = 'search'; - let value = 2; - let result = controller.exprBuilder(param, value); + describe('preview()', () => { + it('should show the dialog summary', () => { + let event = new MouseEvent('click', { + view: $window, + bubbles: true, + cancelable: true + }); + controller.preview(event, travels[0]); - expect(result).toEqual({id: 2}); + expect(controller.$.summary.show).toHaveBeenCalledWith(); }); + }); - it('should return a formated object with the warehouseInFk in case of warehouseInFk', () => { - let param = 'warehouseInFk'; - let value = 3; - let result = controller.exprBuilder(param, value); + describe('getScopeDates()', () => { + it('should return a range of dates', () => { + let days = 2; // never put 1 or anything higher than 2 + let result = controller.getScopeDates(days); - expect(result).toEqual({warehouseInFk: 3}); + let from = new Date(result.shippedFrom).getTime(); + let to = new Date(result.shippedTo).getTime(); + let range = to - from; + + const dayInMilliseconds = 24 * 60 * 60 * 1000; + + let millisecondsPerAddedDay = dayInMilliseconds - 1; + + expect(range - dayInMilliseconds).toEqual(dayInMilliseconds + millisecondsPerAddedDay); }); }); }); diff --git a/modules/travel/front/routes.json b/modules/travel/front/routes.json index 357ffffc2..d9b520816 100644 --- a/modules/travel/front/routes.json +++ b/modules/travel/front/routes.json @@ -24,8 +24,7 @@ "url": "/index?q", "state": "travel.index", "component": "vn-travel-index", - "description": "Travels", - "acl": ["developer"] + "description": "Travels" }, { "url": "/:id", "state": "travel.card", diff --git a/modules/travel/front/search-panel/index.html b/modules/travel/front/search-panel/index.html index bd68fd151..afc041f66 100644 --- a/modules/travel/front/search-panel/index.html +++ b/modules/travel/front/search-panel/index.html @@ -30,7 +30,7 @@ diff --git a/modules/worker/back/models/worker-mana.json b/modules/worker/back/models/worker-mana.json index 8de7c1fe1..b98b2a325 100644 --- a/modules/worker/back/models/worker-mana.json +++ b/modules/worker/back/models/worker-mana.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "bs.workerMana" + "table": "workerMana" } }, "properties": { diff --git a/modules/worker/front/department/index.html b/modules/worker/front/department/index.html index e77d11e12..70932d55b 100644 --- a/modules/worker/front/department/index.html +++ b/modules/worker/front/department/index.html @@ -16,9 +16,6 @@ {{::item.name}} - - - + ng-model="$ctrl.newChild.name" + vn-focus> diff --git a/modules/worker/front/routes.json b/modules/worker/front/routes.json index d117cf18c..6414c9ed2 100644 --- a/modules/worker/front/routes.json +++ b/modules/worker/front/routes.json @@ -51,7 +51,7 @@ "params": { "worker": "$ctrl.worker" }, - "acl": ["developer"] + "acl": ["hr"] }, { "url": "/pbx", "state": "worker.card.pbx", @@ -81,7 +81,8 @@ "url" : "/department", "state": "worker.department", "component": "vn-worker-department", - "description": "Departments" + "description": "Departments", + "acl": ["hr"] }, { "url": "/phones", "state": "worker.card.phones", @@ -89,7 +90,8 @@ "description": "Phones", "params": { "worker": "$ctrl.worker" - } + }, + "acl": ["hr"] }, { "url": "/dms", @@ -101,7 +103,8 @@ "url": "/index", "state": "worker.card.dms.index", "component": "vn-worker-dms-index", - "description": "File management" + "description": "File management", + "acl": ["hr"] }, { "url": "/create", @@ -110,7 +113,8 @@ "description": "Upload file", "params": { "worker": "$ctrl.worker" - } + }, + "acl": ["hr"] }, { "url": "/:dmsId/edit", @@ -119,7 +123,8 @@ "description": "Edit file", "params": { "worker": "$ctrl.worker" - } + }, + "acl": ["hr"] } ] } \ No newline at end of file diff --git a/modules/worker/front/time-control/locale/es.yml b/modules/worker/front/time-control/locale/es.yml index 2f92657dd..1d28b0e2b 100644 --- a/modules/worker/front/time-control/locale/es.yml +++ b/modules/worker/front/time-control/locale/es.yml @@ -5,7 +5,7 @@ Hours: Horas Add time: Añadir hora Week total: Total semana Current week: Semana actual -This time entry will be deleted: Se borrará la hora fichada +This time entry will be deleted: Se eliminará la hora fichada Are you sure you want to delete this entry?: ¿Seguro que quieres eliminarla? Finish at: Termina a las Entry removed: Fichada borrada \ No newline at end of file diff --git a/print/core/mixins/user-locale.js b/print/core/mixins/user-locale.js index f8001aefc..f30bc0b28 100644 --- a/print/core/mixins/user-locale.js +++ b/print/core/mixins/user-locale.js @@ -13,8 +13,11 @@ const userLocale = { methods: { getLocale(clientId) { return db.findOne(` - SELECT lang FROM account.user - WHERE id = ?`, [clientId]).then(rows => { + SELECT IF(u.lang IS NOT NULL, u.lang, LOWER(ct.code)) lang + FROM client c + JOIN country ct ON ct.id = c.countryFk + JOIN account.user u ON u.id = c.id + WHERE c.id = ?`, [clientId]).then(rows => { if (rows) return rows.lang; else return fallbackLocale; diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 812ef0715..1bad225de 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -96,16 +96,22 @@ - {{sale.tag1}} - {{sale.val1}} +
+ {{sale.tag5}} + {{sale.value5}} +
- {{sale.tag2}} - {{sale.val2}} +
+ {{sale.tag6}} + {{sale.value6}} +
- {{sale.tag3}} - {{sale.val3}} +
+ {{sale.tag7}} + {{sale.value7}} +
diff --git a/print/templates/reports/sepa-core/locale/fr.yml b/print/templates/reports/sepa-core/locale/fr.yml index ec6fd11ab..b5cddc38b 100644 --- a/print/templates/reports/sepa-core/locale/fr.yml +++ b/print/templates/reports/sepa-core/locale/fr.yml @@ -1,4 +1,4 @@ -title: Mandat de domiciliation Européene LCR +title: Direct Debit description: En signant ce formulaire de mandat, vous autorisez VERDNATURA LEVANTE SL à envoyer des instructions à votre banque pour débiter votre compte, et (B) votre banque à débiter votre compte conformément aux instructions de VERDNATURA LEVANTE SL.