diff --git a/CHANGELOG.md b/CHANGELOG.md index f203c6457..a2bb2e7e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ + # Changelog All notable changes to this project will be documented in this file. diff --git a/Jenkinsfile b/Jenkinsfile index 6f0a642b4..c8edac0a4 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -24,6 +24,7 @@ node { FROM_GIT = env.JOB_NAME.startsWith('gitea/') RUN_TESTS = !PROTECTED_BRANCH && FROM_GIT RUN_BUILD = PROTECTED_BRANCH && FROM_GIT + // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables echo "NODE_NAME: ${env.NODE_NAME}" echo "WORKSPACE: ${env.WORKSPACE}" @@ -59,7 +60,6 @@ pipeline { } environment { PROJECT_NAME = 'salix' - STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" } stages { stage('Install') { @@ -103,7 +103,7 @@ pipeline { NODE_ENV = '' } steps { - sh 'node back/tests.js --ci --junit --network jenkins' + sh 'node back/tests.js --junit' } post { always { @@ -121,7 +121,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } sh 'docker-compose build back' } @@ -159,7 +159,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } sh 'gulp build' sh 'docker-compose build front' @@ -179,7 +179,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY' sh 'docker-compose push' @@ -203,19 +203,23 @@ pipeline { sh 'npx myt push $NODE_ENV --force --commit' } } - stage('Docker') { + stage('Kubernetes') { when { expression { FROM_GIT } } - environment { - DOCKER_HOST = "${env.SWARM_HOST}" - } steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" + } + withKubeConfig([ + serverUrl: "$KUBERNETES_API", + credentialsId: 'kubernetes', + namespace: 'salix' + ]) { + sh 'kubectl set image deployment/salix-back-$BRANCH_NAME salix-back-$BRANCH_NAME=$REGISTRY/salix-back:$VERSION' + sh 'kubectl set image deployment/salix-front-$BRANCH_NAME salix-front-$BRANCH_NAME=$REGISTRY/salix-front:$VERSION' } - sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}" } } } diff --git a/README.md b/README.md index b420bc44f..b052bd8bf 100644 --- a/README.md +++ b/README.md @@ -11,11 +11,16 @@ Required applications. * Node.js * Docker * Git +* MYT You will need to install globally the following items. ``` $ sudo npm install -g jest gulp-cli ``` +After installing MYT you will need the following item. +``` +$ apt install libkrb5-dev libssl-dev +``` ## Installing dependencies and launching @@ -54,6 +59,12 @@ For end-to-end tests run from project's root. $ npm run test:e2e ``` +## Generate changeLog test → master +``` +$ bash changelog.sh +``` + + ## Visual Studio Code extensions Open Visual Studio Code, press Ctrl+P and paste the following commands. diff --git a/back/methods/chat/sendCheckingPresence.js b/back/methods/chat/sendCheckingPresence.js index 85b66e94b..7ab5d63fe 100644 --- a/back/methods/chat/sendCheckingPresence.js +++ b/back/methods/chat/sendCheckingPresence.js @@ -1,3 +1,5 @@ +const isProduction = require('vn-loopback/server/boot/isProduction'); + module.exports = Self => { Self.remoteMethodCtx('sendCheckingPresence', { description: 'Creates a message in the chat model checking the user status', @@ -37,7 +39,7 @@ module.exports = Self => { if (!recipient) throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`); - if (process.env.NODE_ENV == 'test') + if (!isProduction()) message = `[Test:Environment to user ${userId}] ` + message; const chat = await models.Chat.create({ diff --git a/back/methods/chat/sendQueued.js b/back/methods/chat/sendQueued.js index 9a23af379..abda2ddc1 100644 --- a/back/methods/chat/sendQueued.js +++ b/back/methods/chat/sendQueued.js @@ -1,4 +1,6 @@ const axios = require('axios'); +const isProduction = require('vn-loopback/server/boot/isProduction'); + module.exports = Self => { Self.remoteMethodCtx('sendQueued', { description: 'Send a RocketChat message', @@ -94,7 +96,7 @@ module.exports = Self => { * @return {Promise} - The request promise */ Self.sendMessage = async function sendMessage(senderFk, recipient, message) { - if (process.env.NODE_ENV !== 'production') { + if (!isProduction(false)) { return new Promise(resolve => { return resolve({ statusCode: 200, @@ -149,7 +151,7 @@ module.exports = Self => { * @return {Promise} - The request promise */ Self.getUserStatus = async function getUserStatus(username) { - if (process.env.NODE_ENV !== 'production') { + if (!isProduction(false)) { return new Promise(resolve => { return resolve({ data: { diff --git a/back/methods/dms/deleteTrashFiles.js b/back/methods/dms/deleteTrashFiles.js index 239d654ef..e07f93c90 100644 --- a/back/methods/dms/deleteTrashFiles.js +++ b/back/methods/dms/deleteTrashFiles.js @@ -1,6 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); const fs = require('fs-extra'); const path = require('path'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethod('deleteTrashFiles', { @@ -22,7 +23,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - if (process.env.NODE_ENV == 'test') + if (!isProduction()) throw new UserError(`Action not allowed on the test environment`); const models = Self.app.models; diff --git a/back/methods/docuware/upload.js b/back/methods/docuware/upload.js index 27be72295..0102911e0 100644 --- a/back/methods/docuware/upload.js +++ b/back/methods/docuware/upload.js @@ -1,5 +1,6 @@ const UserError = require('vn-loopback/util/user-error'); const axios = require('axios'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethodCtx('upload', { @@ -119,7 +120,7 @@ module.exports = Self => { ] }; - if (process.env.NODE_ENV != 'production') + if (!isProduction(false)) throw new UserError('Action not allowed on the test environment'); // delete old diff --git a/back/methods/image/scrub.js b/back/methods/image/scrub.js index 99c6bcbf3..3c83b3be7 100644 --- a/back/methods/image/scrub.js +++ b/back/methods/image/scrub.js @@ -1,6 +1,7 @@ const fs = require('fs-extra'); const path = require('path'); const UserError = require('vn-loopback/util/user-error'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethod('scrub', { @@ -43,8 +44,7 @@ module.exports = Self => { Self.scrub = async function(collection, remove, limit, dryRun, skipLock) { const $ = Self.app.models; - const env = process.env.NODE_ENV; - dryRun = dryRun || (env && env !== 'production'); + dryRun = dryRun || !isProduction(false); const instance = await $.ImageCollection.findOne({ fields: ['id'], diff --git a/back/methods/image/upload.js b/back/methods/image/upload.js index 51da327f6..b3cdfb88b 100644 --- a/back/methods/image/upload.js +++ b/back/methods/image/upload.js @@ -1,6 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); const fs = require('fs/promises'); const path = require('path'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethodCtx('upload', { @@ -41,7 +42,7 @@ module.exports = Self => { if (!hasWriteRole) throw new UserError(`You don't have enough privileges`); - if (process.env.NODE_ENV == 'test') + if (!isProduction()) throw new UserError(`Action not allowed on the test environment`); // Upload file to temporary path diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js index 218b6a96b..86bbb7410 100644 --- a/back/methods/mrw-config/cancelShipment.js +++ b/back/methods/mrw-config/cancelShipment.js @@ -39,8 +39,6 @@ module.exports = Self => { const xmlString = response.data; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); - const [resultElement] = xmlDoc.getElementsByTagName('Mensaje'); - - return resultElement.textContent; + return xmlDoc.getElementsByTagName('Mensaje')[0].textContent; }; }; diff --git a/back/methods/mrw-config/createShipment.ejs b/back/methods/mrw-config/createShipment.ejs index bf8a07dab..7468218f2 100644 --- a/back/methods/mrw-config/createShipment.ejs +++ b/back/methods/mrw-config/createShipment.ejs @@ -26,16 +26,24 @@ <%= expeditionData.fi %> <%= expeditionData.clientName %> <%= expeditionData.phone %> + <%= expeditionData.deliveryObservation %> <%= expeditionData.created %> - <%= expeditionData.expeditionDataId %> + <%= expeditionData.reference %> <%= expeditionData.serviceType %> 1 <%= expeditionData.weekDays %> - <%= expeditionData.kg %> + + + <%= mrw.defaultHeight %> + <%= mrw.defaultLength %> + <%= mrw.defaultWidth %> + <%= mrw.defaultWeight %> + + diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index 12263de03..b5bea648d 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -42,9 +42,10 @@ module.exports = Self => { throw new UserError(`Some mrwConfig parameters are not set`); const query = - `SELECT CASE co.code + `SELECT + CASE co.code WHEN 'ES' THEN a.postalCode - WHEN 'PT' THEN LEFT(a.postalCode, 4) + WHEN 'PT' THEN LEFT(a.postalCode, mc.portugalPostCodeTrim) WHEN 'AD' THEN REPLACE(a.postalCode, 'AD', '00') END postalCode, a.city, @@ -55,18 +56,23 @@ module.exports = Self => { c.phone, DATE_FORMAT(t.shipped, '%d/%m/%Y') created, t.shipped, - e.id expeditionId, - LPAD(IF(mw.params IS NULL, ms.serviceType, mw.serviceType), 4 ,'0') serviceType, - IF(mw.weekdays, 'S', 'N') weekDays + CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, + LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, + IF(mw.weekdays, 'S', 'N') weekDays, + oa.description deliveryObservation FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk JOIN mrwService ms ON ms.agencyModeCodeFk = am.code - LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped, '%a') + LEFT JOIN mrwServiceWeekday mw ON mw.weekdays | 1 << WEEKDAY(t.landed) JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id + LEFT JOIN addressObservation oa ON oa.addressFk = a.id + LEFT JOIN observationType ot ON ot.id = oa.observationTypeFk + AND ot.code = 'delivery' JOIN province p ON a.provinceFk = p.id JOIN country co ON co.id = p.countryFk + JOIN mrwConfig mc WHERE e.id = ? LIMIT 1`; @@ -89,14 +95,9 @@ module.exports = Self => { const getLabelResponse = await sendXmlDoc('getLabel', {mrw, shipmentId}, 'text/xml'); const file = getTextByTag(getLabelResponse, 'EtiquetaFile'); - try { - await models.Expedition.updateAll({id: expeditionFk}, {externalId: shipmentId}, myOptions); - if (tx) await tx.commit(); - } catch (error) { - if (tx) await tx.rollback(); - throw error; - } - return file; + if (tx) await tx.commit(); + + return {shipmentId, file}; }; function getTextByTag(xmlDoc, tag) { diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index 0f48bc2d3..f05f9a81d 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -81,9 +81,9 @@ describe('MRWConfig createShipment()', () => { spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop())); - const base64Binary = await models.MrwConfig.createShipment(expedition1.id, options); + const {file} = await models.MrwConfig.createShipment(expedition1.id, options); - expect(base64Binary).toEqual(mockBase64Binary); + expect(file).toEqual(mockBase64Binary); }); it('should fail if mrwConfig has no data', async() => { diff --git a/back/methods/notification/send.js b/back/methods/notification/send.js index b2748477d..1bff7f686 100644 --- a/back/methods/notification/send.js +++ b/back/methods/notification/send.js @@ -1,4 +1,5 @@ const {Email} = require('vn-print'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethod('send', { @@ -70,7 +71,7 @@ module.exports = Self => { const newParams = Object.assign({}, queueParams, sendParams); const email = new Email(queueName, newParams); - if (process.env.NODE_ENV != 'test') + if (isProduction()) await email.send(); await queue.updateAttribute('status', statusSent); diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 8e5ffc095..5581d19ac 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -18,15 +18,10 @@ module.exports = Self => { Self.renewToken = async function(ctx) { const {accessToken: token} = ctx.req; - // Check if current token is valid - - const {renewPeriod, courtesyTime} = await models.AccessTokenConfig.findOne({ - fields: ['renewPeriod', 'courtesyTime'] + const {courtesyTime} = await models.AccessTokenConfig.findOne({ + fields: ['courtesyTime'] }); - const now = Date.now(); - const differenceMilliseconds = now - token.created; - const differenceSeconds = Math.floor(differenceMilliseconds / 1000); - const isNotExceeded = differenceSeconds < renewPeriod - courtesyTime; + const isNotExceeded = await Self.validateToken(ctx); if (isNotExceeded) return token; diff --git a/back/methods/vn-user/validate-token.js b/back/methods/vn-user/validate-token.js new file mode 100644 index 000000000..3b75c7c34 --- /dev/null +++ b/back/methods/vn-user/validate-token.js @@ -0,0 +1,30 @@ +const {models} = require('vn-loopback/server/server'); +module.exports = Self => { + Self.remoteMethodCtx('validateToken', { + description: 'Validates the current logged user token', + accepts: [], + accessType: 'READ', + returns: { + type: 'Boolean', + root: true + }, + http: { + path: `/validateToken`, + verb: 'GET' + } + }); + + Self.validateToken = async function(ctx) { + const {accessToken: token} = ctx.req; + + // Check if current token is valid + const {renewPeriod, courtesyTime} = await models.AccessTokenConfig.findOne({ + fields: ['renewPeriod', 'courtesyTime'] + }); + const now = Date.now(); + const differenceMilliseconds = now - token.created; + const differenceSeconds = Math.floor(differenceMilliseconds / 1000); + const isNotExceeded = differenceSeconds < renewPeriod - courtesyTime; + return isNotExceeded; + }; +}; diff --git a/back/model-config.json b/back/model-config.json index e64386300..b643ab54f 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -186,5 +186,8 @@ }, "AgencyWorkCenter": { "dataSource": "vn" + }, + "RouteConfig": { + "dataSource": "vn" } } diff --git a/back/models/collection.json b/back/models/collection.json index cb8dc3d7c..8a8afeb89 100644 --- a/back/models/collection.json +++ b/back/models/collection.json @@ -1,6 +1,16 @@ { "name": "Collection", "base": "VnModel", + "properties": { + "id": { + "id": true, + "type": "number", + "required": true + }, + "workerFk": { + "type": "number" + } + }, "options": { "mysql": { "table": "collection" diff --git a/back/models/mrw-config.json b/back/models/mrw-config.json index 50cf7e8fc..b0e9754bd 100644 --- a/back/models/mrw-config.json +++ b/back/models/mrw-config.json @@ -27,6 +27,18 @@ }, "subscriberCode": { "type": "string" + }, + "defaultHeight": { + "type": "number" + }, + "defaultLength": { + "type": "number" + }, + "defaultWidth": { + "type": "number" + }, + "defaultWeight": { + "type": "number" } } } diff --git a/back/models/routeConfig.json b/back/models/routeConfig.json new file mode 100644 index 000000000..f3d929749 --- /dev/null +++ b/back/models/routeConfig.json @@ -0,0 +1,18 @@ +{ + "name": "RouteConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "routeConfig" + } + }, + "properties": { + "id": { + "type": "number", + "description": "Identifier" + }, + "kmMax": { + "type": "number" + } + } +} diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 08a4daf54..6ec5642a2 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -15,6 +15,7 @@ module.exports = function(Self) { require('../methods/vn-user/renew-token')(Self); require('../methods/vn-user/share-token')(Self); require('../methods/vn-user/update-user')(Self); + require('../methods/vn-user/validate-token')(Self); require('../methods/vn-user/acls')(Self); Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); diff --git a/back/models/vn-user.json b/back/models/vn-user.json index ebd2ea2f3..415aa6810 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -113,6 +113,13 @@ "principalId": "$everyone", "permission": "ALLOW" }, + { + "property": "validateToken", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + }, { "property": "privileges", "accessType": "*", diff --git a/changelog.sh b/changelog.sh new file mode 100644 index 000000000..8cd7b4716 --- /dev/null +++ b/changelog.sh @@ -0,0 +1,34 @@ +features_types=(chore feat style) +changes_types=(refactor perf) +fix_types=(fix revert) +file="CHANGELOG.md" +file_tmp="temp_log.txt" +file_current_tmp="temp_current_log.txt" + +setType(){ + echo "### $1" >> $file_tmp + arr=("$@") + echo "" > $file_current_tmp + for i in "${arr[@]}" + do + git log --grep="$i" --oneline --no-merges --format="- %s %d by:%an" master..test >> $file_current_tmp + done + # remove duplicates + sort -o $file_current_tmp -u $file_current_tmp + cat $file_current_tmp >> $file_tmp + echo "" >> $file_tmp + # remove tmp current file + [ -e $file_current_tmp ] && rm $file_current_tmp +} + +echo "# Version XX.XX - XXXX-XX-XX" >> $file_tmp +echo "" >> $file_tmp + +setType "Added 🆕" "${features_types[@]}" +setType "Changed 📦" "${changes_types[@]}" +setType "Fixed 🛠️" "${fix_types[@]}" + +cat $file >> $file_tmp +mv $file_tmp $file + + diff --git a/db/.pullinfo.json b/db/.pullinfo.json index f4afbc5fb..27d2c7535 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "288cbd6e8289df083ed5eb1a2c808f7a82ba4c90c8ad9781104808a7a54471fb" + "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" } } } diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index f49e3f0f9..3f2d8e22e 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -3,7 +3,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11031','12f36dc825b6660062e2c86fde9c6b451cb58f0d','2024-05-14 08:25:58','11048'); +INSERT INTO `version` VALUES ('vn-database','11071','60ac8cf6fc77b99b199b27866011b1efe8c961e8','2024-05-28 07:32:50','11074'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -759,6 +759,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10953','06-srt.sql','jenkins@db- INSERT INTO `versionLog` VALUES ('vn-database','10953','07-util.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-04 07:34:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10953','08-vn.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-04 07:34:56',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10953','08-vn2.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-04 07:34:58',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10955','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10956','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-04 07:34:58',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10957','00-aclTicketClone.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-04 07:34:58',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10959','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-03-18 13:32:25',NULL,NULL); @@ -788,22 +789,46 @@ INSERT INTO `versionLog` VALUES ('vn-database','10996','00-dropOrderRecalc.sql', INSERT INTO `versionLog` VALUES ('vn-database','10996','01-dropTicketRecalc.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10996','02-dropTravelRecalc.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10997','00-groupingMode.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:34:21',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11000','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11001','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:26',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11002','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:26',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11003','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:34:21',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11006','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11007','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:34:21',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11008','00-alter.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11010','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11012','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11013','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11014','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11016','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-27 13:16:09',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11018','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:34:21',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11019','00-locker.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11019','01-aclLocker.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11021','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-30 09:07:56',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11022','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11026','00-entryAlter.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11026','01-entryUpdate.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11026','02-entryInternal.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11030','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11031','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11033','00-rollbackAcls.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-07 12:45:45',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11034','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11037','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11038','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11040','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:31',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11044','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:31',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11045','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-10 14:53:29',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11046','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11051','00-sipConfig_callLimit.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-14 14:31:10',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11054','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11055','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11057','00-part.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11057','01-part.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:47',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11057','02-part.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:47',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11057','03-part.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11058','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11061','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11071','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -1090,7 +1115,6 @@ INSERT INTO `roleInherit` VALUES (249,109,18,NULL); INSERT INTO `roleInherit` VALUES (250,109,13,NULL); INSERT INTO `roleInherit` VALUES (251,51,21,NULL); INSERT INTO `roleInherit` VALUES (253,48,49,NULL); -INSERT INTO `roleInherit` VALUES (254,110,1,NULL); INSERT INTO `roleInherit` VALUES (255,110,76,NULL); INSERT INTO `roleInherit` VALUES (256,48,69,NULL); INSERT INTO `roleInherit` VALUES (257,47,111,NULL); @@ -1165,6 +1189,7 @@ INSERT INTO `roleInherit` VALUES (360,101,129,NULL); INSERT INTO `roleInherit` VALUES (361,50,112,NULL); INSERT INTO `roleInherit` VALUES (362,122,15,NULL); INSERT INTO `roleInherit` VALUES (364,35,18,NULL); +INSERT INTO `roleInherit` VALUES (365,123,119,NULL); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -1747,8 +1772,8 @@ INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'); INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (692,'ExpeditionTruck','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'); +INSERT INTO `ACL` VALUES (692,'RoadmapStop','*','*','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (693,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'); @@ -1887,6 +1912,14 @@ INSERT INTO `ACL` VALUES (834,'AgencyMode','*','READ','ALLOW','ROLE','employee') INSERT INTO `ACL` VALUES (835,'Agency','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (836,'Agency','*','WRITE','ALLOW','ROLE','deliveryAssistant'); INSERT INTO `ACL` VALUES (837,'AgencyWorkCenter','*','WRITE','ALLOW','ROLE','deliveryAssistant'); +INSERT INTO `ACL` VALUES (838,'Worker','getAvailablePda','READ','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (839,'Locker','__get__codes','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (840,'Locker','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (841,'Locker','*','*','ALLOW','ROLE','productionBoss'); +INSERT INTO `ACL` VALUES (842,'Worker','__get__locker','READ','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (843,'Worker','__get__locker','READ','ALLOW','ROLE','productionBoss'); +INSERT INTO `ACL` VALUES (844,'RoadmapStop','*','*','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (845,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); @@ -2206,8 +2239,8 @@ INSERT INTO `continent` VALUES (3,'África','AF'); INSERT INTO `continent` VALUES (4,'Europa','EU'); INSERT INTO `continent` VALUES (5,'Oceanía','OC'); -INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,25,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (23,'CMA','CAMARA',13,14,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (31,'it','INFORMATICA',4,5,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (34,'accounting','CONTABILIDAD',6,7,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); @@ -2217,28 +2250,28 @@ INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',12,35,NULL,72,1,1,1,11,1 INSERT INTO `department` VALUES (38,'picking','SACADO',15,16,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (39,'packing','ENCAJADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',36,37,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (43,'VT','VENTAS',38,69,NULL,0,0,0,1,15,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (44,'management','GERENCIA',70,71,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (46,'delivery','REPARTO',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',76,77,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (43,'VT','VENTAS',38,71,NULL,0,0,0,1,16,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (44,'management','GERENCIA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (46,'delivery','REPARTO',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',78,79,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',39,40,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',19,20,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL); INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',21,22,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL); -INSERT INTO `department` VALUES (58,'CMP','CAMPOS',84,87,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',88,89,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (58,'CMP','CAMPOS',86,89,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (61,NULL,'VNH',90,93,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (61,NULL,'VNH',92,95,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',96,97,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',23,24,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',96,97,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (80,'vallesTeam','EQUIPO ESPAÑA 5',43,44,4250,72,0,0,2,0,43,'/1/43/','jvp_equipo',1,'equipojvalles@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL); -INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (89,NULL,'COORDINACION',100,101,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (90,NULL,'TRAILER',91,92,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',98,99,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',43,44,4250,0,0,0,2,0,43,'/1/43/','es5_equipo',1,'es5@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL); +INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',100,101,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (89,NULL,'COORDINACION',102,103,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (90,NULL,'TRAILER',93,94,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',25,26,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',45,46,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',47,48,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',0,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); @@ -2246,20 +2279,20 @@ INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',49,50,24065, INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',51,52,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',53,54,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',55,56,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (125,'miriamMarTeam','EQUIPO ESPAÑA 3',57,58,1118,0,0,0,2,0,43,'/1/43/','mir_equipo',0,'equipomirgir@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); +INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',57,58,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',0,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',27,28,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',29,30,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (130,NULL,'REVISION',31,32,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',85,86,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',59,60,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',61,62,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); -INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',63,64,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); +INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',87,88,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',61,62,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',63,64,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); +INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',104,105,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',106,107,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (137,'sorter','SORTER',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (139,'soriaTeam','EQUIPO ESPAÑA 4',65,66,3803,0,0,0,2,0,43,'/1/43/','jss_equipo',1,'equipojsoria@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); -INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',67,68,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); +INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',69,70,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (141,NULL,'PREVIA',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index 5b1b600b1..39b7d4a8c 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -1300,7 +1300,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimState','juan@d INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','company','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','buffer','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greuge','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','item','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select,Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','item','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select,Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -1400,6 +1400,12 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','waste','alexm@db-prox INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInConfig','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyDetail','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyReview','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','chat','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','roadmapStop','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyWorkCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1595,10 +1601,7 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','editorFk', INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','recycledPlastic','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','nonRecycledPlastic','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','minQuantity','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','size','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','originFk','0000-00-00 00:00:00','Select,Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','longName','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','name','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','id','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','warehouseFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','shipped','0000-00-00 00:00:00','Update'); @@ -1873,7 +1876,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaParcialMak INSERT IGNORE INTO `procs_priv` VALUES ('','vn','palletizerBoss','packingsite_startcollection','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','sale_calculatecomponent','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','manaspellersrequery','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','adminBoss','packageinvoicing','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','packinglistswitch','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','previoussticker_get','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','productioncontrol','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); @@ -1976,7 +1978,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionscan_ad INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionscan_list','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expeditionscan_put','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','cmrpallet_add','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemtrash','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getbalance','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_checkroute','FUNCTION','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','addnotefromdelivery','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2029,7 +2030,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionscan_add' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionscan_list','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expeditionscan_put','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','cmrpallet_add','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemtrash','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','item_getbalance','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','expedition_checkroute','FUNCTION','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','addnotefromdelivery','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 1cb5c2964..b61cbcc5c 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -6458,7 +6458,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_add`( IN vStarted DATE, - IN vEnded DATE) + IN vEnded DATE +) BEGIN /** * Añade las ventas que se realizaron entre 2 fechas a la tabla bs.sale @@ -6467,64 +6468,55 @@ BEGIN * @param vEnded Fecha de fin * */ - DECLARE vLoopDate DATE; - DECLARE vLoopDateTime DATETIME; - IF vStarted < (util.VN_CURDATE() - INTERVAL 5 YEAR) OR vStarted > vEnded THEN CALL util.throw('Wrong date'); END IF; - SET vLoopDate = vStarted; - DELETE FROM sale WHERE dated BETWEEN vStarted AND vEnded; - WHILE vLoopDate <= vEnded DO - SET vLoopDateTime = util.dayEnd(vLoopDate); - - REPLACE sale( - saleFk, - amount, - surcharge, - dated, - typeFk, - clientFk, - companyFk, - margin - )WITH calculatedSales AS( - SELECT s.id saleFk, - SUM(IF(ct.isBase, s.quantity * sc.value, 0)) amount, - SUM(IF(ct.isBase, 0, s.quantity * sc.value)) surcharge, - s.total pvp, - DATE(t.shipped) dated, - i.typeFk, - t.clientFk, - t.companyFk, - SUM(IF(ct.isMargin, s.quantity * sc.value, 0 )) marginComponents - FROM vn.ticket t - STRAIGHT_JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk - WHERE t.shipped BETWEEN vLoopDate AND vLoopDateTime - AND s.quantity <> 0 - AND ic.merchandise - GROUP BY s.id - )SELECT saleFk, - amount, - surcharge, - dated, - typeFk, - clientFk, - companyFk, - marginComponents + amount + surcharge - pvp - FROM calculatedSales; - - SET vLoopDate = vLoopDate + INTERVAL 1 DAY; - END WHILE; + REPLACE sale( + saleFk, + amount, + surcharge, + dated, + typeFk, + clientFk, + companyFk, + margin + )WITH calculatedSales AS( + SELECT s.id saleFk, + CAST(SUM(IF(ct.isBase, s.quantity * sc.value, 0)) AS DECIMAL(10, 3)) amount, + CAST(SUM(IF(ct.isBase, 0, s.quantity * sc.value)) AS DECIMAL(10, 3)) surcharge, + s.total, + DATE(t.shipped) dated, + i.typeFk, + t.clientFk, + t.companyFk, + CAST(SUM(IF(ct.isMargin, s.quantity * sc.value, 0 )) AS DECIMAL(10, 3)) marginComponents + FROM vn.ticket t + STRAIGHT_JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.saleComponent sc ON sc.saleFk = s.id + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk + WHERE t.shipped BETWEEN vStarted AND vEnded + AND s.quantity <> 0 + AND ic.merchandise + GROUP BY s.id + )SELECT saleFk, + amount, + surcharge, + dated, + typeFk, + clientFk, + companyFk, + IF (marginComponents IS NULL, + 0, + CAST(marginComponents + amount + surcharge - total AS DECIMAL(10, 3))) + FROM calculatedSales; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8276,7 +8268,7 @@ BEGIN vPrinterFk, IFNULL(right(`t`.`routeFk`, 3),0), if (@vVolume := vn.ticketTotalVolume(t.id) > 1.5, @vVolume, IFNULL( rm.beachFk, 0)), - LEFT(IFNULL(et.description ,replace(`z`.`name`, 'ZONA ', 'Z')),14) truckName, + LEFT(IFNULL(rs.description ,replace(`z`.`name`, 'ZONA ', 'Z')),14) truckName, t.clientFk , ifnull(c.mobile, ifnull(a.mobile, ifnull(c.phone, a.phone))), LEFT(p.name, 20), @@ -8288,7 +8280,7 @@ BEGIN JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p ON p.id = a.provinceFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN vn.beach b ON b.code = rm.beachFk LEFT JOIN vn.`zone`z ON z.id = t.zoneFk JOIN vn.agencyMode am ON t.agencyModeFk = am.id @@ -11167,6 +11159,7 @@ CREATE TABLE `order` ( `isPaid` tinyint(1) NOT NULL DEFAULT 0, `payed` datetime DEFAULT NULL, `created` timestamp NULL DEFAULT current_timestamp(), + `observations` text DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `catalogueFk` (`catalogueFk`), CONSTRAINT `order_ibfk_1` FOREIGN KEY (`catalogueFk`) REFERENCES `catalogue` (`id`) ON UPDATE CASCADE @@ -15107,7 +15100,7 @@ BEGIN -- Código redundante - DO vn.till_new( + CALL vn.till_new( vCustomer ,vBank ,vAmount / 100 @@ -16028,7 +16021,7 @@ SET character_set_client = utf8; 1 AS `permit`, 1 AS `type`, 1 AS `context`, - 1 AS `incominglimit`, + 1 AS `call-limit`, 1 AS `pickupgroup`, 1 AS `directmedia`, 1 AS `insecure`, @@ -16060,7 +16053,7 @@ CREATE TABLE `sipConfig` ( `permit` varchar(95) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `type` enum('user','peer','friend') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `context` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - `incomingLimit` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `call-limit` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `pickupGroup` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `directMedia` enum('yes','no') DEFAULT NULL, `insecure` varchar(45) NOT NULL, @@ -17926,7 +17919,7 @@ BEGIN IFNULL(c.street, ''), c.accountingAccount, @fi := IF(cu.code = LEFT(TRIM(c.fi), 2) AND c.isVies, MID(TRIM(c.fi), 3, LENGTH(TRIM(c.fi))-1), TRIM(c.fi)), - IF(c.isVies, CONCAT(cu.code, @fi ), TRIM(c.fi)), + IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), IFNULL(c.postcode, ''), IFNULL(c.city, ''), IFNULL(pr.CodigoProvincia, ''), @@ -17964,7 +17957,7 @@ BEGIN IFNULL(s.street, ''), s.account, @nif := IF(co.code = LEFT(TRIM(s.nif), 2), MID(TRIM(s.nif), 3, LENGTH(TRIM(s.nif))-1), TRIM(s.nif)), - IF(s.isVies, CONCAT(co.code, @nif), TRIM(s.nif)), + IF(s.isVies, CONCAT(IFNULL(co.viesCode,co.code), @nif), TRIM(s.nif)), IFNULL(s.postCode,''), IFNULL(s.city, ''), IFNULL(pr.CodigoProvincia, ''), @@ -20277,14 +20270,14 @@ BEGIN DECLARE vDayMinute INT; - SELECT HOUR(IFNULL(et.ETD, z.`hour`)) * 60 + MINUTE(IFNULL(et.ETD, z.`hour`)) INTO vDayMinute + SELECT HOUR(IFNULL(rs.ETD, z.`hour`)) * 60 + MINUTE(IFNULL(rs.ETD, z.`hour`)) INTO vDayMinute FROM vn.expedition e JOIN vn.ticket t ON e.ticketFk = t.id JOIN vn.`zone` z ON z.id = t.zoneFk LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk - LEFT JOIN vn.expeditionTruck et ON rm.expeditionTruckFk = et.id + LEFT JOIN vn.roadmapStop rs ON rm.expeditionTruckFk = rs.id WHERE e.id = vExpeditionFk; RETURN vDayMinute; @@ -21803,8 +21796,8 @@ BEGIN SET @dm := (24 * 60) - 10; - UPDATE vn.expeditionTruck et - SET et.eta = timestampadd(MINUTE ,@dm := 1 + @dm,util.VN_CURDATE()) + UPDATE vn.roadmapStop rs + SET rs.eta = timestampadd(MINUTE ,@dm := 1 + @dm,util.VN_CURDATE()) WHERE description LIKE 'PRU%' ; DELETE FROM srt.movingLog ; @@ -26143,6 +26136,7 @@ CREATE TABLE `absenceType` ( `holidayEntitlementRate` decimal(3,2) DEFAULT 1.00, `isNaturalDay` tinyint(1) DEFAULT 0 COMMENT 'Para el cálculo de los salarios de los repartidores', `isCalculate` tinyint(1) DEFAULT 0 COMMENT 'Para el cálculo de los salarios de los repartidores', + `isFestiveEligible` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Para marcar un tipo de absence', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -27514,7 +27508,7 @@ CREATE TABLE `buy` ( `packing` int(11) NOT NULL DEFAULT 1 CHECK (`packing` > 0), `grouping` smallint(5) unsigned NOT NULL DEFAULT 1, `groupingMode` enum('grouping','packing') DEFAULT NULL, - `containerFk` smallint(5) unsigned DEFAULT NULL, + `containerFk__` smallint(5) unsigned DEFAULT NULL, `comissionValue` decimal(10,3) NOT NULL DEFAULT 0.000, `packageValue` decimal(10,3) NOT NULL DEFAULT 0.000, `location` varchar(5) DEFAULT NULL, @@ -27539,7 +27533,7 @@ CREATE TABLE `buy` ( KEY `CompresId_Trabajador` (`workerFk`), KEY `Id_Cubo` (`packagingFk`), KEY `Id_Entrada` (`entryFk`), - KEY `container_id` (`containerFk`), + KEY `container_id` (`containerFk__`), KEY `buy_edi_id` (`ektFk`), KEY `itemFk_entryFk` (`itemFk`,`entryFk`), KEY `buy_fk_4_idx` (`deliveryFk`), @@ -27547,7 +27541,6 @@ CREATE TABLE `buy` ( KEY `buy_itemFk_IDX` (`itemFk`) USING BTREE, KEY `buy_fk_editor` (`editorFk`), CONSTRAINT `buy_FK` FOREIGN KEY (`itemOriginalFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `buy_FK_1` FOREIGN KEY (`containerFk`) REFERENCES `vn2008`.`container__` (`container_id`) ON UPDATE CASCADE, CONSTRAINT `buy_ektFk` FOREIGN KEY (`ektFk`) REFERENCES `edi`.`ekt` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `buy_fk_4` FOREIGN KEY (`deliveryFk`) REFERENCES `edi`.`deliveryInformation` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL, CONSTRAINT `buy_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), @@ -28290,6 +28283,7 @@ CREATE TABLE `clientConfig` ( `defaultIsTaxDataChecked` tinyint(1) DEFAULT NULL, `defaultHasCoreVnl` tinyint(1) DEFAULT NULL, `defaultMandateTypeFk` smallint(5) DEFAULT NULL, + `monthsToDisableUser` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `clientNewConfigPayMethod_FK` (`defaultPayMethodFk`), KEY `clientNewConfigMandateType_FK` (`defaultMandateTypeFk`), @@ -29358,19 +29352,18 @@ CREATE TABLE `conveyorType` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `coolerPathDetail` +-- Table structure for table `coolerPathDetail__` -- -DROP TABLE IF EXISTS `coolerPathDetail`; +DROP TABLE IF EXISTS `coolerPathDetail__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `coolerPathDetail` ( +CREATE TABLE `coolerPathDetail__` ( `id` int(11) NOT NULL AUTO_INCREMENT, `coolerPathFk` int(11) NOT NULL DEFAULT 1, `hallway` varchar(3) NOT NULL, PRIMARY KEY (`coolerPathFk`,`hallway`), - UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`id`), - CONSTRAINT `coolerPathDetail_FK` FOREIGN KEY (`coolerPathFk`) REFERENCES `vn2008`.`cooler_path__` (`cooler_path_id`) ON UPDATE CASCADE + UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -29398,9 +29391,10 @@ DROP TABLE IF EXISTS `country`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `country` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `country` varchar(25) NOT NULL, + `name` varchar(25) NOT NULL, `CEE` tinyint(1) NOT NULL DEFAULT 1, `code` varchar(2) NOT NULL, + `viesCode` varchar(2) DEFAULT NULL, `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT 1, `politicalCountryFk__` mediumint(8) unsigned DEFAULT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)', `geoFk` int(11) DEFAULT NULL, @@ -29410,11 +29404,12 @@ CREATE TABLE `country` ( `continentFk` tinyint(4) DEFAULT NULL, `a3Code` int(11) DEFAULT NULL COMMENT 'Código país para a3', `isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1, + `country` varchar(25) GENERATED ALWAYS AS (`name`) VIRTUAL, PRIMARY KEY (`id`), UNIQUE KEY `country_unique` (`code`), KEY `Id_Paisreal` (`politicalCountryFk__`), KEY `currency_id_fk_idx` (`currencyFk`), - KEY `country_Ix4` (`country`), + KEY `country_Ix4` (`name`), KEY `continent_id_fk_idx` (`continentFk`), KEY `country_FK_1` (`geoFk`), CONSTRAINT `continent_id_fk` FOREIGN KEY (`continentFk`) REFERENCES `continent` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, @@ -29664,7 +29659,7 @@ CREATE TABLE `deliveryNote` ( `supervisorFk` int(10) unsigned NOT NULL, `departmentFk` int(11) NOT NULL, `invoiceInFk` mediumint(8) unsigned DEFAULT NULL, - `farmingFk` int(10) unsigned DEFAULT NULL, + `farmingFk__` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_albaran_Proveedores_idx` (`supplierFk`), KEY `fk_albaran_empresa1_idx` (`companyFk`), @@ -29674,9 +29669,9 @@ CREATE TABLE `deliveryNote` ( KEY `fk_albaran_Trabajadores2_idx` (`supervisorFk`), KEY `fk_albaran_department1_idx` (`departmentFk`), KEY `fk_albaran_recibida_idx` (`invoiceInFk`), - KEY `albaran_FK` (`farmingFk`), + KEY `albaran_FK` (`farmingFk__`), CONSTRAINT `albaranCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, - CONSTRAINT `albaran_FK` FOREIGN KEY (`farmingFk`) REFERENCES `farming` (`id`), + CONSTRAINT `albaran_FK` FOREIGN KEY (`farmingFk__`) REFERENCES `farming` (`id`), CONSTRAINT `albaran_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE, CONSTRAINT `fk_albaran_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fk_albaran_Trabajadores2` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, @@ -29923,6 +29918,7 @@ CREATE TABLE `deviceProductionConfig` ( `id` int(10) unsigned NOT NULL, `isAllUsersallowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Permite que cualquier usuario pueda loguearse', `isTractorHuntingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Habilita el modo cazador para usuarios que no se han logeado un tractor para sacar', + `maxDevicesPerUser` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `deviceProductionConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -29996,16 +29992,18 @@ DROP TABLE IF EXISTS `deviceProductionUser`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `deviceProductionUser` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `deviceProductionFk` int(11) NOT NULL, `userFk` int(10) unsigned NOT NULL, `created` timestamp NULL DEFAULT current_timestamp(), `editorFk` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`deviceProductionFk`), - UNIQUE KEY `deviceProductionUser_UN` (`userFk`), + `simSerialNumber` text DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `deviceProductionUser_unique` (`deviceProductionFk`), KEY `userFgn_idx` (`userFk`), KEY `deviceProductionUser_fk_editor` (`editorFk`), - CONSTRAINT `deviceProductionUser_FK` FOREIGN KEY (`deviceProductionFk`) REFERENCES `deviceProduction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `deviceProductionUser_PK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `deviceProductionUser_deviceProduction_FK` FOREIGN KEY (`deviceProductionFk`) REFERENCES `deviceProduction` (`id`), CONSTRAINT `deviceProductionUser_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -30804,43 +30802,6 @@ SET character_set_client = utf8; 1 AS `rate` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `exchangeReportSource` --- - -DROP TABLE IF EXISTS `exchangeReportSource`; -/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `exchangeReportSource` AS SELECT - 1 AS `dated`, - 1 AS `amountIn`, - 1 AS `rateIn`, - 1 AS `amountOut`, - 1 AS `rateOut`, - 1 AS `amountEntry`, - 1 AS `rateEntry`, - 1 AS `rateECB` */; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `exchangeReportSourcePrevious` --- - -DROP TABLE IF EXISTS `exchangeReportSourcePrevious`; -/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `exchangeReportSourcePrevious` AS SELECT - 1 AS `dated`, - 1 AS `amountIn`, - 1 AS `rateIn`, - 1 AS `amountOut`, - 1 AS `rateOut`, - 1 AS `amountEntry`, - 1 AS `rateEntry` */; -SET character_set_client = @saved_cs_client; - -- -- Table structure for table `excuse` -- @@ -30995,7 +30956,7 @@ CREATE TABLE `expeditionPallet` ( `isPrint` tinyint(4) NOT NULL DEFAULT 2, PRIMARY KEY (`id`), KEY `expeditionPallet_fk1_idx` (`truckFk`), - CONSTRAINT `expeditionPallet_fk1` FOREIGN KEY (`truckFk`) REFERENCES `expeditionTruck` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + CONSTRAINT `expeditionPallet_fk1` FOREIGN KEY (`truckFk`) REFERENCES `roadmapStop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -31190,33 +31151,23 @@ SET character_set_client = utf8; SET character_set_client = @saved_cs_client; -- --- Table structure for table `expeditionTruck` +-- Temporary table structure for view `expeditionTruck` -- DROP TABLE IF EXISTS `expeditionTruck`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `expeditionTruck` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `roadmapFk` int(10) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned DEFAULT NULL, - `eta` datetime DEFAULT NULL COMMENT 'Estimated time of arrival', - `description` varchar(45) NOT NULL, - `bufferFk` int(11) DEFAULT NULL COMMENT 'buffer destino de las cajas', - `created` timestamp NULL DEFAULT current_timestamp(), - `userFk` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `expeditionTruck_idx1` (`eta`), - KEY `expeditionTruck_FK` (`bufferFk`), - KEY `expeditionTruck_FK_1` (`warehouseFk`), - KEY `expeditionTruck_FK_2` (`roadmapFk`), - KEY `expeditionTruck_FK_3` (`userFk`), - CONSTRAINT `expeditionTruck_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_2` FOREIGN KEY (`roadmapFk`) REFERENCES `roadmap` (`id`) ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales'; -/*!40101 SET character_set_client = @saved_cs_client */; +/*!50001 DROP VIEW IF EXISTS `expeditionTruck`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `expeditionTruck` AS SELECT + 1 AS `id`, + 1 AS `roadmapFk`, + 1 AS `warehouseFk`, + 1 AS `eta`, + 1 AS `description`, + 1 AS `bufferFk`, + 1 AS `created`, + 1 AS `userFk` */; +SET character_set_client = @saved_cs_client; -- -- Temporary table structure for view `expeditionTruck_Control` @@ -32128,12 +32079,12 @@ CREATE TABLE `invoiceInConfig` ( `id` int(10) unsigned NOT NULL, `retentionRate` int(3) NOT NULL, `retentionName` varchar(25) NOT NULL, - `sageWithholdingFk` smallint(6) NOT NULL, + `sageFarmerWithholdingFk` smallint(6) NOT NULL, `daysAgo` int(10) unsigned DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix', `taxRowLimit` int(11) DEFAULT 4 COMMENT 'Número máximo de líneas de IVA que puede tener una factura', PRIMARY KEY (`id`), - KEY `invoiceInConfig_sageWithholdingFk` (`sageWithholdingFk`), - CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageWithholdingFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE, + KEY `invoiceInConfig_sageWithholdingFk` (`sageFarmerWithholdingFk`), + CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageFarmerWithholdingFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `invoiceInConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -32574,8 +32525,8 @@ CREATE TABLE `item` ( `lastUsed` datetime DEFAULT current_timestamp(), `weightByPiece` int(10) unsigned DEFAULT NULL COMMENT 'peso por defecto para un articulo por tallo/unidad', `editorFk` int(10) unsigned DEFAULT NULL, - `recycledPlastic` int(11) DEFAULT NULL, - `nonRecycledPlastic` int(11) DEFAULT NULL, + `recycledPlastic` decimal(10,2) DEFAULT NULL, + `nonRecycledPlastic` decimal(10,2) DEFAULT NULL, `minQuantity` int(10) unsigned DEFAULT NULL COMMENT 'Cantidad mínima para una línea de venta', `isBoxPickingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'FALSE: using item.packingOut TRUE: boxPicking using itemShelving.packing', PRIMARY KEY (`id`), @@ -33674,6 +33625,22 @@ SET character_set_client = utf8; 1 AS `totalAmount` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `ledgerCompany` +-- + +DROP TABLE IF EXISTS `ledgerCompany`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ledgerCompany` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `fiscalYear` int(10) unsigned NOT NULL COMMENT 'Año del ejercicio contable', + `bookEntry` int(10) unsigned NOT NULL DEFAULT 1 COMMENT 'Contador asiento contable', + PRIMARY KEY (`id`), + UNIQUE KEY `ledgerCompany_unique` (`fiscalYear`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Contador para asientos contables'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `ledgerConfig` -- @@ -33682,9 +33649,28 @@ DROP TABLE IF EXISTS `ledgerConfig`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ledgerConfig` ( - `lastBookEntry` int(11) NOT NULL, + `lastBookEntry__` int(11) NOT NULL COMMENT '@deprecated 2024-05-28 refs #7400 Modificar contador asientos contables', `maxTolerance` decimal(10,2) NOT NULL, - PRIMARY KEY (`lastBookEntry`) + PRIMARY KEY (`lastBookEntry__`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `locker` +-- + +DROP TABLE IF EXISTS `locker`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `locker` ( + `id` int(100) NOT NULL AUTO_INCREMENT, + `code` varchar(10) DEFAULT NULL, + `gender` enum('M','F') DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`), + UNIQUE KEY `workerFk` (`workerFk`), + CONSTRAINT `locker_ibfk_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -34550,9 +34536,9 @@ DROP TABLE IF EXISTS `packaging`; CREATE TABLE `packaging` ( `id` varchar(10) NOT NULL, `volume` decimal(10,2) DEFAULT NULL CHECK (`volume` >= coalesce(`width`,1) * coalesce(`depth`,1) * coalesce(`height`,1)), - `width` decimal(10,2) DEFAULT 0.00, - `depth` decimal(10,2) DEFAULT 0.00, - `height` decimal(10,2) DEFAULT 0.00, + `width` decimal(10,2) DEFAULT NULL, + `depth` decimal(10,2) DEFAULT NULL, + `height` decimal(10,2) DEFAULT NULL, `value` decimal(10,2) DEFAULT 0.00, `isPackageReturnable` tinyint(1) NOT NULL DEFAULT 0, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), @@ -35936,7 +35922,7 @@ CREATE TABLE `province` ( `name` varchar(30) NOT NULL, `countryFk` mediumint(8) unsigned NOT NULL, `warehouseFk` smallint(6) unsigned DEFAULT NULL COMMENT 'warehouse responsable de las rutas', - `zoneFk` tinyint(4) DEFAULT NULL, + `zoneFk` int(11) DEFAULT NULL, `geoFk` int(11) DEFAULT NULL, `autonomyFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), @@ -35947,7 +35933,7 @@ CREATE TABLE `province` ( KEY `province_FK` (`autonomyFk`), CONSTRAINT `province_FK` FOREIGN KEY (`autonomyFk`) REFERENCES `autonomy` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `province_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, - CONSTRAINT `province_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `vn2008`.`zones__` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `province_zone_FK` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36314,6 +36300,35 @@ CREATE TABLE `roadmap` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Troncales diarios que se contratan'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `roadmapStop` +-- + +DROP TABLE IF EXISTS `roadmapStop`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `roadmapStop` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `roadmapFk` int(10) unsigned DEFAULT NULL, + `warehouseFk` smallint(6) unsigned DEFAULT NULL, + `eta` datetime DEFAULT NULL COMMENT 'Estimated time of arrival', + `description` varchar(45) NOT NULL, + `bufferFk` int(11) DEFAULT NULL COMMENT 'buffer destino de las cajas', + `created` timestamp NULL DEFAULT current_timestamp(), + `userFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `expeditionTruck_idx1` (`eta`), + KEY `expeditionTruck_FK` (`bufferFk`), + KEY `expeditionTruck_FK_1` (`warehouseFk`), + KEY `expeditionTruck_FK_2` (`roadmapFk`), + KEY `expeditionTruck_FK_3` (`userFk`), + CONSTRAINT `expeditionTruck_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `expeditionTruck_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `expeditionTruck_FK_2` FOREIGN KEY (`roadmapFk`) REFERENCES `roadmap` (`id`) ON UPDATE CASCADE, + CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `role` -- @@ -36356,7 +36371,7 @@ DROP TABLE IF EXISTS `route`; CREATE TABLE `route` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `workerFk` int(10) unsigned DEFAULT NULL, - `firstEditorFk` int(10) unsigned NOT NULL COMMENT 'Usuario creador de la ruta', + `firstEditorFk` int(10) unsigned DEFAULT NULL, `created` date NOT NULL, `vehicleFk` int(10) unsigned DEFAULT NULL, `agencyModeFk` int(11) DEFAULT NULL, @@ -36386,13 +36401,17 @@ CREATE TABLE `route` ( KEY `route_idxIsOk` (`isOk`), KEY `route_WorkCenterFk_idx` (`commissionWorkCenterFk`), KEY `route_fk_editor` (`editorFk`), + KEY `route_vehicleFk` (`vehicleFk`), + KEY `route_firstEditorFk` (`firstEditorFk`), CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_WorkCenterFk` FOREIGN KEY (`commissionWorkCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE, + CONSTRAINT `route_firstEditorFk` FOREIGN KEY (`firstEditorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `route_fk5` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), 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, - CONSTRAINT `route_invoiceInFk` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE + CONSTRAINT `route_invoiceInFk` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `route_vehicleFk` FOREIGN KEY (`vehicleFk`) REFERENCES `vehicle` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36694,7 +36713,7 @@ CREATE TABLE `routesMonitor` ( CONSTRAINT `routesMonitor_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `routesMonitor_FK_1` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`code`) ON UPDATE CASCADE, CONSTRAINT `routesMonitor_FK_2` FOREIGN KEY (`beachFk`) REFERENCES `beach` (`code`) ON UPDATE CASCADE, - CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`expeditionTruckFk`) REFERENCES `expeditionTruck` (`id`) ON UPDATE CASCADE, + CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`expeditionTruckFk`) REFERENCES `roadmapStop` (`id`) ON UPDATE CASCADE, CONSTRAINT `routesMonitor_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36723,6 +36742,7 @@ CREATE TABLE `sale` ( `isAdded` tinyint(1) NOT NULL DEFAULT 0, `total` decimal(10,2) GENERATED ALWAYS AS (`price` * `quantity` * (100 - `discount`) / 100) VIRTUAL, `editorFk` int(10) unsigned DEFAULT NULL, + `problem` set('hasItemShortage','hasComponentLack','hasItemDelay','hasRounding','hasItemLost') NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `Id_Ticket` (`ticketFk`), KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`), @@ -38047,7 +38067,7 @@ CREATE TABLE `supplier` ( `countryFk` mediumint(8) unsigned DEFAULT NULL, `nif` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `isOfficial` tinyint(1) NOT NULL DEFAULT 1, - `isFarmer` tinyint(1) NOT NULL DEFAULT 0, + `isFarmer__` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'refs #7345 @deprecated 2024-05-10 - Utilizar withholdingSageFk', `retAccount` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `phone` varchar(16) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `commission` float NOT NULL DEFAULT 0, @@ -38627,6 +38647,8 @@ CREATE TABLE `ticket` ( `clonedFrom` int(11) DEFAULT NULL, `cmrFk` int(11) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, + `problem` set('hasTicketRequest','isFreezed','hasRisk','hasHighRisk','isTaxDataChecked','isTooLittle') NOT NULL DEFAULT '', + `risk` decimal(10,2) DEFAULT NULL COMMENT 'cache calculada con el riesgo del cliente', PRIMARY KEY (`id`), KEY `Id_Cliente` (`clientFk`), KEY `Id_Consigna` (`addressFk`), @@ -39663,15 +39685,22 @@ CREATE TABLE `travelConfig` ( `warehouseOutFk` smallint(6) unsigned NOT NULL DEFAULT 60 COMMENT 'Warehouse destino', `agencyFk` int(11) NOT NULL DEFAULT 1378 COMMENT 'Agencia por defecto', `companyFk` int(10) unsigned NOT NULL DEFAULT 442 COMMENT 'Compañía por defecto', + `devalueWarehouseOutFk` smallint(6) unsigned DEFAULT NULL COMMENT 'Datos del travel para las entradas generadas al devaluar artículos de A1 a A2', + `devalueAgencyModeFk` int(11) DEFAULT NULL, + `devalueRef` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `travelConfig_FK` (`warehouseInFk`), KEY `travelConfig_FK_1` (`warehouseOutFk`), KEY `travelConfig_FK_2` (`agencyFk`), KEY `travelConfig_FK_3` (`companyFk`), + KEY `travelConfig_agencyMode_FK` (`devalueAgencyModeFk`), + KEY `travelConfig_warehouse_FK` (`devalueWarehouseOutFk`), CONSTRAINT `travelConfig_FK` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `travelConfig_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `travelConfig_FK_2` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `travelConfig_FK_3` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelConfig_agencyMode_FK` FOREIGN KEY (`devalueAgencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `travelConfig_warehouse_FK` FOREIGN KEY (`devalueWarehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `travelConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -40375,12 +40404,10 @@ CREATE TABLE `worker` ( `sex` enum('M','F') NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', `businessFk` int(11) DEFAULT NULL, `balance` decimal(10,2) DEFAULT NULL, - `locker` int(10) unsigned DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`), UNIQUE KEY `worker_business` (`businessFk`), - UNIQUE KEY `locker` (`locker`), KEY `sub` (`sub`), KEY `boss_idx` (`bossFk`), KEY `worker_FK` (`labelerFk__`), @@ -40777,7 +40804,7 @@ CREATE TABLE `workerLog` ( `action` set('insert','update','delete') NOT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `description` text DEFAULT NULL, - `changedModel` enum('Worker','Calendar','WorkerTimeControlMail','Business','WorkerDms','WorkerTimeControl') NOT NULL DEFAULT 'Worker', + `changedModel` enum('Worker','Calendar','WorkerTimeControlMail','Business','WorkerDms','WorkerTimeControl','Locker') NOT NULL DEFAULT 'Worker', `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), `changedModelId` int(11) NOT NULL, @@ -41593,42 +41620,7 @@ CREATE TABLE `zoneWarehouse` ( -- Dumping events for database 'vn' -- /*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `clientsDisable` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clientsDisable` ON SCHEDULE EVERY 1 MONTH STARTS '2023-06-01 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - UPDATE account.user u - JOIN client c ON c.id = u.id - LEFT JOIN account.account a ON a.id = u.id - SET u.active = FALSE - WHERE c.typeFk = 'normal' - AND a.id IS NULL - AND u.active - AND c.created < util.VN_CURDATE() - INTERVAL 12 MONTH - AND u.id NOT IN ( - SELECT DISTINCT c.id - FROM client c - LEFT JOIN ticket t ON t.clientFk = c.id - WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL 12 MONTH - OR shipped > util.VN_CURDATE() - INTERVAL 12 MONTH - ); -END */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -/*!50106 DROP EVENT IF EXISTS `client_unassignSalesPerson` */;; +/*!50106 DROP EVENT IF EXISTS `client_unassignSalesPerson` */; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; /*!50003 SET @saved_cs_results = @@character_set_results */ ;; @@ -41646,6 +41638,24 @@ DELIMITER ;; /*!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 `client_userDisable` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `client_userDisable` ON SCHEDULE EVERY 1 MONTH STARTS '2023-06-01 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL client_userDisable() */ ;; +/*!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 `collection_make` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -44973,6 +44983,46 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `sale_hasComponentLack` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `sale_hasComponentLack`(vSelf INT +) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Check if a sales line has all the required components. + * + * @param vSelf Id de sale + * @return BOOL + */ + DECLARE vHasComponentLack TINYINT(1); + + WITH componentRequired AS( + SELECT COUNT(*) total + FROM vn.component + WHERE isRequired + )SELECT SUM(IF(c.isRequired, TRUE, FALSE)) <> cr.total INTO vHasComponentLack + FROM vn.sale s + JOIN componentRequired cr + LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id + LEFT JOIN vn.component c ON c.id = sc.componentFk + WHERE s.id = vSelf; + + RETURN vHasComponentLack; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `specie_IsForbidden` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45747,6 +45797,42 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticket_isTooLittle` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_isTooLittle`(vSelf INT +) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Check if the ticket is small based on the volume and amount parameters. + * + * @param vSelf Id ticket + * @return BOOL + */ + DECLARE vIsTooLittle TINYINT(1); + + SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume + OR IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle + FROM ticket t + LEFT JOIN saleVolume sv ON sv.ticketFk = t.id + JOIN volumeConfig vc + WHERE t.id = vSelf; + + RETURN vIsTooLittle; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `till_new` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -46359,61 +46445,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP FUNCTION IF EXISTS `xdiario_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 = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `xdiario_new`(vAsiento INT, - vDated DATE, - vSubaccount VARCHAR(12), - vAccount VARCHAR(12), - vConcept VARCHAR(25), - vDebit DOUBLE, - vCredit DOUBLE, - vEuro DOUBLE, - vSerie CHAR(1), - vInvoice VARCHAR(8), - vVat DOUBLE, - vRe DOUBLE, - vAux TINYINT, - vCompany INT -) RETURNS int(11) - NO SQL -BEGIN - IF vAsiento IS NULL THEN - CALL vn.ledger_next(vAsiento); - END IF; - - INSERT INTO XDiario - SET ASIEN = vAsiento, - FECHA = vDated, - SUBCTA = vSubaccount, - CONTRA = vAccount, - CONCEPTO = vConcept, - EURODEBE = vDebit, - EUROHABER = vCredit, - BASEEURO = vEuro, - SERIE = vSerie, - FACTURA = vInvoice, - IVA = vVat, - RECEQUIV = vRe, - AUXILIAR = IF(vAux = FALSE, NULL, '*'), - MONEDAUSO = 2, - empresa_id = vCompany; - - RETURN vAsiento; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `zoneGeo_new` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -46958,7 +46989,7 @@ BEGIN DECLARE vEnded DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); SELECT ag.id agency_id, - CONCAT(RPAD(c.country, 16,' _') ,' ',ag.name) Agencia, + CONCAT(RPAD(c.name, 16,' _') ,' ',ag.name) Agencia, COUNT(*) expediciones, SUM(t.packages) Bultos, SUM(tpe.boxes) Faltan @@ -48133,6 +48164,76 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_clone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_clone`(vEntryFk INT) +BEGIN +/** + * Clone buys to an entry + * + * @param vEntryFk The entry id + * @table tmp.buy(id) + */ + INSERT INTO buy( + entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk) + SELECT vEntryFk, + b.itemFk, + b.quantity, + b.buyingValue, + b.freightValue, + b.isIgnored, + b.stickers, + b.packagingFk, + b.packing, + b.`grouping`, + b.groupingMode, + b.comissionValue, + b.packageValue, + b.price1, + b.price2, + b.price3, + b.minPrice, + b.isChecked, + b.location, + b.weight, + b.itemOriginalFk + FROM tmp.buy tb + JOIN vn.buy b ON b.id = tb.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 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `buy_getSplit` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -48492,7 +48593,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; - CREATE TEMPORARY TABLE tmp.buyRecalc + CREATE TEMPORARY TABLE tmp.buyRecalc SELECT vBuyFk id; CALL buy_recalcPrices(); @@ -49382,7 +49483,7 @@ BEGIN WHERE cs.description = 'Anulado' AND c.created < v2Months; - DELETE FROM expeditionTruck WHERE eta < v3Months; + DELETE FROM roadmapStop WHERE eta < v3Months; DELETE FROM XDiario WHERE FECHA < v3Months OR FECHA IS NULL; -- Borrar travels sin entradas @@ -50553,7 +50654,7 @@ BEGIN c.credit, CAST(r.risk AS DECIMAL (10,2)) risk, CAST(c.credit - r.risk AS DECIMAL (10,2)) difference, - co.country + co.name country FROM client c JOIN tmp.risk r ON r.clientFk = c.id JOIN country co ON co.id = c.countryFk @@ -50706,6 +50807,52 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `client_userDisable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `client_userDisable`() +BEGIN +/** +* Desactiva los clientes inactivos en los últimos X meses. +*/ + DECLARE vMonths INT; + + SELECT monthsToDisableUser INTO vMonths + FROM clientConfig; + + IF vMonths IS NULL THEN + CALL util.throw('Config parameter not set'); + END IF; + + UPDATE account.user u + JOIN client c ON c.id = u.id + LEFT JOIN account.account a ON a.id = u.id + SET u.active = FALSE + WHERE c.typeFk = 'normal' + AND a.id IS NULL + AND u.active + AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH + AND u.id NOT IN ( + SELECT DISTINCT c.id + FROM client c + LEFT JOIN ticket t ON t.clientFk = c.id + WHERE c.salesPersonFk IS NOT NULL + OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH + OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH + ); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `cmrPallet_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51024,6 +51171,7 @@ BEGIN BEGIN IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); + CALL util.debugAdd('releaseLock', vLockName); -- Tmp END IF; RESIGNAL; @@ -51515,6 +51663,7 @@ BEGIN BEGIN IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); + CALL util.debugAdd('releaseLock', vLockName); -- Tmp END IF; RESIGNAL; @@ -52182,11 +52331,12 @@ BEGIN FROM tPendingDuedates vp LEFT JOIN supplier s ON s.id = vp.supplierFk LEFT JOIN client c ON c.fi = s.nif - LEFT JOIN clientRisk cr ON cr.clientFk = c.id + LEFT JOIN clientRisk cr ON cr.clientFk = c.id AND cr.companyFk = vp.companyFk LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON be.id = sa.bankEntityFk - LEFT JOIN country co ON co.id = be.countryFk; + LEFT JOIN country co ON co.id = be.countryFk + GROUP BY vp.id; DROP TEMPORARY TABLE tOpeningBalances; DROP TEMPORARY TABLE tPendingDuedates; @@ -52420,7 +52570,7 @@ BEGIN 10 * p.height as height, IFNULL(t.routeFk,am.agencyFk) routeFk, hour(e.created) * 60 + minute(e.created), - IFNULL(et.description , a.name), + IFNULL(rs.description , a.name), IFNULL(t.routeFk,am.agencyFk) criterion, IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e @@ -52430,7 +52580,7 @@ BEGIN LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.agency a ON a.id = am.agencyFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded @@ -52557,7 +52707,7 @@ BEGIN cac.invoiced billedAnnually, c.dueDay, cgd.grade, - c2.country + c2.name country FROM tmp.clientGetDebt cgd LEFT JOIN tmp.risk r ON r.clientFk = cgd.clientFk JOIN client c ON c.id = cgd.clientFk @@ -53406,127 +53556,121 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTaxBooking`(vDuaFk INT) BEGIN DECLARE vBookNumber INT; - DECLARE vBookDated DATE; - DECLARE vDiff DECIMAL(10,2); - DECLARE vApunte BIGINT; - - SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated - FROM dua + DECLARE vBookDated DATE; + DECLARE vDiff DECIMAL(10,2); + DECLARE vApunte BIGINT; + + SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) + INTO vBookNumber, vBookDated + FROM dua WHERE id = vDuaFk; - + IF vBookNumber IS NULL OR NOT vBookNumber THEN - CALL ledger_next(vBookNumber); + CALL ledger_next(YEAR(vBookDated), vBookNumber); END IF; -- Apunte de la aduana - INSERT INTO XDiario( - ASIEN, - FECHA, - SUBCTA, - CONCEPTO, - EUROHABER, - SERIE, - empresa_id, - CLAVE, - FACTURA) + ASIEN, + FECHA, + SUBCTA, + CONCEPTO, + EUROHABER, + SERIE, + empresa_id, + CLAVE, + FACTURA) + SELECT vBookNumber, + d.bookEntried, + '4700000999', + CONCAT('DUA ',d.`code`), + sum(dt.base * dt.rate / 100) EUROHABER, + 'R', + d.companyFk, + vDuaFk, + vDuaFk + FROM duaTax dt + JOIN dua d ON d.id = dt.duaFk + WHERE dt.duaFk = vDuaFk; - SELECT - vBookNumber, - d.bookEntried, - '4700000999', - CONCAT('DUA ',d.`code`), - sum(dt.base * dt.rate / 100) EUROHABER, - 'R', - d.companyFk, - vDuaFk, - vDuaFk - FROM duaTax dt - JOIN dua d ON d.id = dt.duaFk - WHERE dt.duaFk = vDuaFk; - - -- Apuntes por tipo de IVA y proveedor - - INSERT INTO XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - FECHA_EX, - FECHA_OP, - FACTURAEX, - NFACTICK, - L340, - LDIFADUAN, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - empresa_id, - FECREGCON - ) - - SELECT - vBookNumber ASIEN, - vBookDated FECHA, - tr.account SUBCTA, - '4330002067' CONTRA, - sum(dt.tax) EURODEBE, - sum(dt.base) BASEEURO, - CONCAT('DUA nº',d.code) CONCEPTO, - d.id FACTURA, - dt.rate IVA, - '*' AUXILIAR, - 'D' SERIE, - d.issued FECHA_EX, - d.operated FECHA_OP, - d.code FACTURAEX, - 1 NFACTICK, - 1 L340, - TRUE LDIFADUAN, - 1 TIPOCLAVE, - 1 TIPOEXENCI, - 1 TIPONOSUJE, - 5 TIPOFACT, - 1 TIPORECTIF, - IF(c.code = 'ES', 1, 4) TERIDNIF, - s.nif TERNIF, - s.name TERNOM, - d.companyFk, - d.booked FECREGCON - FROM duaTax dt - JOIN dua d ON dt.duaFk = d.id - JOIN (SELECT account, rate - FROM - (SELECT rate, account - FROM invoiceInTaxBookingAccount ta - WHERE ta.effectived <= vBookDated - AND taxAreaFk = 'WORLD' - ORDER BY ta.effectived DESC - LIMIT 10000000000000000000 - ) tba - GROUP BY rate + -- Apuntes por tipo de IVA y proveedor + INSERT INTO XDiario( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EURODEBE, + BASEEURO, + CONCEPTO, + FACTURA, + IVA, + AUXILIAR, + SERIE, + FECHA_EX, + FECHA_OP, + FACTURAEX, + NFACTICK, + L340, + LDIFADUAN, + TIPOCLAVE, + TIPOEXENCI, + TIPONOSUJE, + TIPOFACT, + TIPORECTIF, + TERIDNIF, + TERNIF, + TERNOM, + empresa_id, + FECREGCON) + SELECT vBookNumber ASIEN, + vBookDated FECHA, + tr.account SUBCTA, + '4330002067' CONTRA, + SUM(dt.tax) EURODEBE, + SUM(dt.base) BASEEURO, + CONCAT('DUA nº',d.code) CONCEPTO, + d.id FACTURA, + dt.rate IVA, + '*' AUXILIAR, + 'D' SERIE, + d.issued FECHA_EX, + d.operated FECHA_OP, + d.code FACTURAEX, + 1 NFACTICK, + 1 L340, + TRUE LDIFADUAN, + 1 TIPOCLAVE, + 1 TIPOEXENCI, + 1 TIPONOSUJE, + 5 TIPOFACT, + 1 TIPORECTIF, + IF(c.code = 'ES', 1, 4) TERIDNIF, + s.nif TERNIF, + s.name TERNOM, + d.companyFk, + d.booked FECREGCON + FROM duaTax dt + JOIN dua d ON dt.duaFk = d.id + JOIN (SELECT account, rate + FROM + (SELECT rate, account + FROM invoiceInTaxBookingAccount ta + WHERE ta.effectived <= vBookDated + AND taxAreaFk = 'WORLD' + ORDER BY ta.effectived DESC + LIMIT 10000000000000000000 + ) tba + GROUP BY rate ) tr ON tr.rate = dt.rate - JOIN supplier s ON s.id = d.companyFk - JOIN country c ON c.id = s.countryFk - WHERE d.id = vDuaFk - GROUP BY dt.rate; + JOIN supplier s ON s.id = d.companyFk + JOIN country c ON c.id = s.countryFk + WHERE d.id = vDuaFk + GROUP BY dt.rate; SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte FROM XDiario WHERE ASIEN = vBookNumber; - + UPDATE XDiario SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, EURODEBE = EURODEBE - vDiff @@ -53535,7 +53679,6 @@ BEGIN UPDATE dua SET ASIEN = vBookNumber WHERE id = vDuaFk; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54025,8 +54168,8 @@ BEGIN * Clones an entry header. * * @param vSelf The entry id + * @param OUT vNewEntryFk The new entry id * @param vTravelFk Travel for the new entry or %NULL to use the source entry travel - * @param vNewEntryFk The new entry id */ INSERT INTO entry( travelFk, @@ -54104,62 +54247,21 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_copyBuys`(vSelf INT, vCopyTo INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_copyBuys`(vSelf INT, vDestinationEntryFk INT) BEGIN /** - * Copies an entry buys to another buy. + * Copies all buys from an entry to an entry. * * @param vSelf The entry id - * @param vCopyTo The destination entry id + * @param vDestinationEntryFk The destination entry id */ - INSERT INTO buy( - entryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - containerFk, - comissionValue, - packageValue, - packagingFk, - price1, - price2, - price3, - minPrice, - isChecked, - location, - weight, - itemOriginalFk - ) - SELECT vCopyTo, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - containerFk, - comissionValue, - packageValue, - packagingFk, - price1, - price2, - price3, - minPrice, - isChecked, - location, - weight, - itemOriginalFk + CREATE OR REPLACE TEMPORARY TABLE tmp.buy + SELECT id FROM buy WHERE entryFk = vSelf; + + CALL buy_clone(vDestinationEntryFk); + DROP TEMPORARY TABLE tmp.buy; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54203,7 +54305,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -54223,7 +54324,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -54590,7 +54690,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, packagingFk, @@ -54611,7 +54710,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, packagingFk, @@ -54648,7 +54746,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -54667,7 +54764,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -54892,7 +54988,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -54919,7 +55014,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -55680,7 +55774,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45)) BEGIN - INSERT INTO vn.expeditionTruck(eta,description) + INSERT INTO vn.roadmapStop(eta,description) VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription); END ;; @@ -55704,10 +55798,10 @@ BEGIN SELECT id truckFk, eta, - description Destino - FROM expeditionTruck - WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - ORDER BY eta; + description Destino + FROM roadmapStop + WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) + ORDER BY eta; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55814,8 +55908,8 @@ BEGIN am.name zonaRuta, t.routeFk ruta, rm.beachFk ubicacion, - et.eta , - et.description camion, + rs.eta , + rs.description camion, vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas @@ -55827,7 +55921,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; END ;; @@ -55900,8 +55994,8 @@ BEGIN am.name zonaRuta, t.routeFk ruta, rm.beachFk ubicacion, - et.eta , - et.description camion, + rs.eta , + rs.description camion, vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas, @@ -55914,7 +56008,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; END ;; @@ -55944,120 +56038,6 @@ BEGIN WHERE r.workerFk = workerFk ORDER BY r.id DESC LIMIT 1; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `fv_pca` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `fv_pca`() -BEGIN - -DECLARE done INT DEFAULT FALSE; - -DECLARE vTicketFk INT; -DECLARE vSaleFk INT; -DECLARE vClonTicket INT DEFAULT 0; - -DECLARE cur1 CURSOR FOR -SELECT s.ticketFk, s.id - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - WHERE t.shipped BETWEEN '2020-10-18' AND '2020-10-31' - AND it.code IN ('ANT','ANS','ORQ','TRO') - and t.warehouseFk = 1; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - -OPEN cur1; - -FETCH cur1 INTO vTicketFk, vSaleFk; - - WHILE done = 0 DO - - SELECT t.id INTO vClonTicket - FROM vn.ticket t - JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) - WHERE t.warehouseFk = 44 - LIMIT 1; - - SELECT vTicketFk, vClonTicket; - - IF vClonTicket = 0 THEN - - INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - companyFk, - landed, - zoneFk, - zonePrice, - zoneBonus, - routeFk - ) - SELECT - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - 44, - companyFk, - landed, - zoneFk, - zonePrice, - zoneBonus, - routeFk - - FROM ticket - WHERE id = vTicketFk; - - SET vClonTicket = LAST_INSERT_ID(); - - SELECT 'lstID', vClonTicket; - /* - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vTicketFk, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN ticket t ON t.addressFk = ao.addressFk - WHERE t.id = vClonTicket; -*/ - INSERT INTO ticketLog - SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', - description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); - - END IF; - - UPDATE vn.sale - SET ticketFk = vClonTicket - WHERE id = vSaleFk; - - SET vClonTicket = 0; - - SET done = 0; - FETCH cur1 INTO vTicketFk, vSaleFk; - - END WHILE; - - CLOSE cur1; - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57197,26 +57177,26 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vInvoiceInFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`( + IN vInvoiceInFk INT +) BEGIN DECLARE vRate DOUBLE DEFAULT 1; - DECLARE vDated DATE; DECLARE vExpenseFk VARCHAR(10); - SELECT MAX(rr.dated) INTO vDated - FROM referenceRate rr - JOIN invoiceIn ii ON ii.id = vInvoiceInFk - WHERE rr.dated <= ii.issued - AND rr.currencyFk = ii.currencyFk ; - - IF vDated THEN - SELECT `value` INTO vRate - FROM referenceRate - WHERE dated = vDated; - END IF; + WITH rate AS( + SELECT MAX(rr.dated) dated, ii.currencyFk + FROM vn.invoiceIn ii + JOIN vn.referenceRate rr ON rr.currencyFk = ii.currencyFk + WHERE ii.id = vInvoiceInFk + AND rr.dated <= ii.issued + ) SELECT `value` INTO vRate + FROM vn.referenceRate rr + JOIN rate r ON r.dated = rr.dated + AND r.currencyFk = rr.currencyFk; SELECT id INTO vExpenseFk - FROM vn.expense + FROM expense WHERE `name` = 'Adquisición mercancia Extracomunitaria' GROUP BY id LIMIT 1; @@ -57224,19 +57204,25 @@ BEGIN DELETE FROM invoiceInTax WHERE invoiceInFk = vInvoiceInFk; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) - SELECT ii.id, - SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase, - vExpenseFk, - IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa, - taxTypeSageFk, + INSERT INTO invoiceInTax( + invoiceInFk, + taxableBase, + expenseFk, + foreignValue, + taxTypeSageFk, transactionTypeSageFk + )SELECT ii.id, + SUM(b.buyingValue * b.quantity) / vRate taxableBase, + vExpenseFk, + IF(ii.currencyFk = 1, + NULL, + SUM(b.buyingValue * b.quantity )), + taxTypeSageFk, + transactionTypeSageFk FROM invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id JOIN supplier s ON s.id = e.supplierFk JOIN buy b ON b.entryFk = e.id - LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk - AND rr.dated = ii.issued WHERE ii.id = vInvoiceInFk HAVING taxableBase IS NOT NULL; END ;; @@ -57328,6 +57314,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_booking`(vSelf INT) BEGIN DECLARE vBookNumber INT; + DECLARE vFiscalYear INT; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY @@ -57382,7 +57369,8 @@ BEGIN LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva WHERE ii.id = vSelf; - CALL vn.ledger_next(vBookNumber); + SELECT YEAR(bookEntried) INTO vFiscalYear FROM tInvoiceIn LIMIT 1; + CALL ledger_next(vFiscalYear, vBookNumber); -- Apunte del proveedor INSERT INTO XDiario( @@ -57728,22 +57716,24 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutBooking`(IN vInvoice INT) BEGIN -/* Asienta la factura emitida -* -* param vInvoice factura_id -*/ +/** + * Asienta una factura emitida + * + * @param vInvoice Id invoiceOut + */ DECLARE vBookNumber INT; - DECLARE vExpenseConcept VARCHAR(50); - DECLARE vSpainCountryFk INT; - DECLARE vOldBookNumber INT; + DECLARE vExpenseConcept VARCHAR(50); + DECLARE vSpainCountryFk INT; + DECLARE vOldBookNumber INT; + DECLARE vFiscalYear INT; - SELECT id INTO vSpainCountryFk FROM country WHERE code = 'ES'; + SELECT id INTO vSpainCountryFk FROM country WHERE `code` = 'ES'; - SELECT ASIEN + SELECT ASIEN INTO vOldBookNumber FROM XDiario x JOIN invoiceOut io ON io.id = vInvoice - WHERE x.SERIE = io.serial + WHERE x.SERIE = io.serial AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1) LIMIT 1; @@ -57753,140 +57743,133 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS rs; CREATE TEMPORARY TABLE rs - SELECT - c.accountingAccount AS clientBookingAccount, - io.amount as totalAmount, - CONCAT('n/fra ', io.ref) as simpleConcept, - CONCAT('n/fra ', io.ref, ' ', c.name) as Concept, - io.serial AS SERIE, - io.issued AS FECHA_EX, - io.issued AS FECHA_OP, - io.issued AS FECHA, - 1 AS NFACTICK, - IF(ic.correctingFk,'D','') AS TIPOOPE, - io.siiTrascendencyInvoiceOutFk AS TIPOCLAVE, - io.cplusTaxBreakFk AS TIPOEXENCI, - io.cplusSubjectOpFk AS TIPONOSUJE, - io.siiTypeInvoiceOutFk AS TIPOFACT, - ic.cplusRectificationTypeFk AS TIPORECTIF, + SELECT c.accountingAccount clientBookingAccount, + io.amount totalAmount, + CONCAT('n/fra ', io.ref) simpleConcept, + CONCAT('n/fra ', io.ref, ' ', c.name) Concept, + io.serial SERIE, + io.issued FECHA_EX, + io.issued FECHA_OP, + io.issued FECHA, + 1 NFACTICK, + IF(ic.correctingFk,'D','') TIPOOPE, + io.siiTrascendencyInvoiceOutFk TIPOCLAVE, + io.cplusTaxBreakFk TIPOEXENCI, + io.cplusSubjectOpFk TIPONOSUJE, + io.siiTypeInvoiceOutFk TIPOFACT, + ic.cplusRectificationTypeFk TIPORECTIF, io.companyFk, - RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, - IF(c.countryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember,2,4)) AS TERIDNIF, - CONCAT(IF(ct.isUeeMember AND c.countryFk <> vSpainCountryFk,ct.code,''),c.fi) AS TERNIF, - c.socialName AS TERNOM, - ior.serial AS SERIE_RT, - RIGHT(ior.ref, LENGTH(ior.ref) - 1) AS FACTU_RT, - ior.issued AS FECHA_RT, - IF(ior.id,TRUE,FALSE) AS RECTIFICA + RIGHT(io.ref, LENGTH(io.ref) - 1) invoiceNum, + IF(c.countryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember,2,4)) TERIDNIF, + CONCAT(IF(ct.isUeeMember AND c.countryFk <> vSpainCountryFk,ct.code,''),c.fi) TERNIF, + c.socialName TERNOM, + ior.serial SERIE_RT, + RIGHT(ior.ref, LENGTH(ior.ref) - 1) FACTU_RT, + ior.issued FECHA_RT, + IF(ior.id,TRUE,FALSE) RECTIFICA FROM invoiceOut io JOIN invoiceOutSerial ios ON ios.code = io.serial JOIN client c ON c.id = io.clientFk JOIN country ct ON ct.id = c.countryFk LEFT JOIN invoiceCorrection ic ON ic.correctingFk = io.id - LEFT JOIN invoiceOut ior ON ior.id = ic.correctedFk + LEFT JOIN invoiceOut ior ON ior.id = ic.correctedFk WHERE io.id = vInvoice; - CALL vn.ledger_next(vBookNumber); - + SELECT YEAR(FECHA) INTO vFiscalYear FROM rs LIMIT 1; + CALL ledger_next(vFiscalYear, vBookNumber); -- Linea del cliente INSERT INTO XDiario( - ASIEN, - FECHA, - SUBCTA, - EURODEBE, - CONCEPTO, - FECHA_EX, - FECHA_OP, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, + ASIEN, + FECHA, + SUBCTA, + EURODEBE, + CONCEPTO, + FECHA_EX, + FECHA_OP, + empresa_id) + SELECT vBookNumber, rs.FECHA, - rs.clientBookingAccount AS SUBCTA, - rs.totalAmount AS EURODEBE, - rs.simpleConcept AS CONCEPTO, + rs.clientBookingAccount, + rs.totalAmount, + rs.simpleConcept, rs.FECHA_EX, rs.FECHA_OP, - rs.companyFk AS empresa_id + rs.companyFk FROM rs; -- Lineas de gasto INSERT INTO XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - CONCEPTO, - FECHA_EX, - FECHA_OP, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, - rs.FECHA, - ioe.expenseFk AS SUBCTA, - rs.clientBookingAccount AS CONTRA, - ioe.amount AS EUROHABER, - rs.Concept AS CONCEPTO, - rs.FECHA_EX, - rs.FECHA_OP, - rs.companyFk AS empresa_id - FROM rs - JOIN invoiceOutExpense ioe - WHERE ioe.invoiceOutFk = vInvoice; + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EUROHABER, + CONCEPTO, + FECHA_EX, + FECHA_OP, + empresa_id) + SELECT vBookNumber, + rs.FECHA, + ioe.expenseFk, + rs.clientBookingAccount, + ioe.amount, + rs.Concept, + rs.FECHA_EX, + rs.FECHA_OP, + rs.companyFk + FROM rs + JOIN invoiceOutExpense ioe + WHERE ioe.invoiceOutFk = vInvoice; - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenseConcept - FROM expense e - JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id - WHERE ioe.invoiceOutFk = vInvoice; + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenseConcept + FROM expense e + JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id + WHERE ioe.invoiceOutFk = vInvoice; - -- Lineas de IVA + -- Lineas de IVA INSERT INTO XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - RECEQUIV, - AUXILIAR, - SERIE, - SERIE_RT, - FACTU_RT, - RECTIFICA, - FECHA_RT, - FECHA_OP, - FECHA_EX, - TIPOOPE, - NFACTICK, - TERIDNIF, - TERNIF, - TERNOM, - L340, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EUROHABER, + BASEEURO, + CONCEPTO, + FACTURA, + IVA, + RECEQUIV, + AUXILIAR, + SERIE, + SERIE_RT, + FACTU_RT, + RECTIFICA, + FECHA_RT, + FECHA_OP, + FECHA_EX, + TIPOOPE, + NFACTICK, + TERIDNIF, + TERNIF, + TERNOM, + L340, + TIPOCLAVE, + TIPOEXENCI, + TIPONOSUJE, + TIPOFACT, + TIPORECTIF, + empresa_id) + SELECT vBookNumber ASIEN, rs.FECHA, - iot.pgcFk AS SUBCTA, - rs.clientBookingAccount AS CONTRA, - iot.vat AS EUROHABER, - iot.taxableBase AS BASEEURO, - CONCAT(vExpenseConcept,' : ',rs.Concept) AS CONCEPTO, - rs.invoiceNum AS FACTURA, - IF(pe2.equFk,0,pgc.rate) AS IVA, - IF(pe2.equFk,0,pgce.rate) AS RECEQUIV, - IF(pgc.mod347,'','*') AS AUXILIAR, + iot.pgcFk SUBCTA, + rs.clientBookingAccount CONTRA, + iot.vat EUROHABER, + iot.taxableBase BASEEURO, + CONCAT(vExpenseConcept,' : ',rs.Concept) CONCEPTO, + rs.invoiceNum FACTURA, + IF(pe2.equFk,0,pgc.rate) IVA, + IF(pe2.equFk,0,pgce.rate) RECEQUIV, + IF(pgc.mod347,'','*') AUXILIAR, rs.SERIE, rs.SERIE_RT, rs.FACTU_RT, @@ -57895,28 +57878,28 @@ BEGIN rs.FECHA_OP, rs.FECHA_EX, rs.TIPOOPE, - rs.NFACTICK, + rs.NFACTICK, rs.TERIDNIF, rs.TERNIF, rs.TERNOM, - pgc.mod340 AS L340, - pgc.siiTrascendencyInvoiceOutFk AS TIPOCLAVE, - pgc.cplusTaxBreakFk as TIPOEXENCI, + pgc.mod340 L340, + pgc.siiTrascendencyInvoiceOutFk TIPOCLAVE, + pgc.cplusTaxBreakFk TIPOEXENCI, rs.TIPONOSUJE, rs.TIPOFACT, rs.TIPORECTIF, - rs.companyFk AS empresa_id + rs.companyFk FROM rs JOIN invoiceOutTax iot JOIN pgc ON pgc.code = iot.pgcFk LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado LEFT JOIN pgc pgce ON pgce.code = pe.equFk - LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. + LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. WHERE iot.invoiceOutFk = vInvoice; - - UPDATE invoiceOut - SET booked = util.VN_CURDATE() - WHERE id = vInvoice; + + UPDATE invoiceOut + SET booked = util.VN_CURDATE() + WHERE id = vInvoice; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58918,11 +58901,12 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.warehouse w ON w.id = sc.warehouseFk - WHERE sc.id = vSectorFk - AND ish.visible > 0 + WHERE ish.visible > 0 AND ish.itemFk = vItemFk GROUP BY ish.id - ORDER BY sh.priority DESC, + ORDER BY + (sc.id = vSectorFk) DESC, + sh.priority DESC, ish.created, p.pickingOrder; END ;; @@ -59362,7 +59346,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`( vSectorFk INT ) -proc:BEGIN +BEGIN /** * Calcula la información detallada respecto un sector. * @@ -59375,37 +59359,24 @@ proc:BEGIN DECLARE vWarehouseFk INT DEFAULT 0; DECLARE vSonSectorFk INT; DECLARE vWorkerFk INT; - - SELECT s.workerFk - INTO vWorkerFk - FROM vn.sector s + + SELECT s.workerFk INTO vWorkerFk + FROM sector s WHERE s.id = vSectorFk; - SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk - FROM vn.worker w - JOIN vn.sector s ON s.code = w.code - WHERE s.id = vSectorFk; - - SELECT s.id INTO vSectorFk - FROM vn.sector s - WHERE s.warehouseFk = vWarehouseFk - AND s.isMain; - SELECT COUNT(*) INTO hasFatherSector - FROM vn.sector + FROM sector WHERE sonFk = vSectorFk; - + SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk - FROM vn.sector + FROM sector WHERE id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - - DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + IF hasFatherSector THEN - CREATE TEMPORARY TABLE tmp.itemShelvingRadar + CREATE OR REPLACE TEMPORARY TABLE tItemShelvingRadar (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT * @@ -59414,57 +59385,77 @@ proc:BEGIN i.longName, i.size, i.subName producer, - IFNULL(a.available,0) available, - SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs, - SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, - IF(it.isPackaging, NULL, IFNULL(v.visible,0)) as visible, - vSectorFk sectorFk - FROM vn.itemShelvingStock iss - JOIN vn.sector s ON s.id = iss.sectorFk - JOIN vn.item i on i.id = iss.itemFk - JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) - LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk - LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + IFNULL(a.available, 0) available, + SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible, 0), 0)) upstairs, + SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible, 0), 0)) downstairs, + IF(it.isPackaging, NULL, IFNULL(v.visible, 0)) visible, + vSectorFk sectorFk, + ish.isChecked, + sub.isAllChecked + FROM itemShelvingStock iss + JOIN itemShelving ish ON ish.shelvingFk = iss.shelvingFk + LEFT JOIN ( + SELECT itemFk, + IF( + COUNT(*) = SUM(IF(isChecked >= 0, 1, 0)), + TRUE, + FALSE + ) isAllChecked + FROM itemShelving is2 + GROUP BY itemFk + ) sub ON sub.itemFk = ish.itemFk + JOIN sector s ON s.id = iss.sectorFk + JOIN item i ON i.id = iss.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN cache.available a ON a.item_id = iss.itemFk + AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk + AND v.calc_id = vCalcVisibleFk WHERE vSectorFk IN (iss.sectorFk, s.sonFk) GROUP BY iss.itemFk - UNION ALL - - SELECT v.item_id, + SELECT v.item_id, i.longName, i.size, - i.subName producer, - IFNULL(a.available,0) as available, - 0 upstairs, - 0 downstairs, - IF(it.isPackaging, NULL, v.visible) visible, - vSectorFk as sectorFk + i.subName, + IFNULL(a.available, 0), + 0, + 0, + IF(it.isPackaging, NULL, v.visible), + vSectorFk, + NULL, + NULL FROM cache.visible v - JOIN vn.item i on i.id = v.item_id - JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk - LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk + JOIN item i ON i.id = v.item_id + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemShelvingStock iss ON iss.itemFk = v.item_id + AND iss.warehouseFk = vWarehouseFk + LEFT JOIN cache.available a ON a.item_id = v.item_id + AND a.calc_id = vCalcAvailableFk WHERE v.calc_id = vCalcVisibleFk AND iss.itemFk IS NULL AND it.isInventory - ) sub GROUP BY itemFk; + ) sub + GROUP BY itemFk; SELECT ishr.*, - CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, - CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente - FROM tmp.itemShelvingRadar ishr - JOIN vn.item i ON i.id = ishr.itemFk - LEFT JOIN (SELECT s.itemFk, sum(s.quantity) as notPickedYed - FROM vn.ticket t - JOIN vn.ticketStateToday tst ON tst.ticketFk = t.id - JOIN vn.sale s ON s.ticketFk = t.id - WHERE t.warehouseFk = vWarehouseFk - AND tst.alertLevel = 0 - GROUP BY s.itemFk - ) sub ON sub.itemFk = ishr.itemFk - ORDER BY i.typeFk, i.longName; + CAST(visible - upstairs - downstairs AS DECIMAL(10, 0)) nicho, + CAST(downstairs - IFNULL(notPickedYed, 0) AS DECIMAL(10, 0)) pendiente + FROM tItemShelvingRadar ishr + JOIN item i ON i.id = ishr.itemFk + LEFT JOIN ( + SELECT s.itemFk, SUM(s.quantity) notPickedYed + FROM ticket t + JOIN ticketStateToday tst ON tst.ticketFk = t.id + JOIN alertLevel al ON al.id = tst.alertLevel + JOIN sale s ON s.ticketFk = t.id + WHERE t.warehouseFk = vWarehouseFk + AND al.code = 'FREE' + GROUP BY s.itemFk + ) sub ON sub.itemFk = ishr.itemFk + ORDER BY i.typeFk, i.longName; ELSE - CREATE TEMPORARY TABLE tmp.itemShelvingRadar + CREATE OR REPLACE TEMPORARY TABLE tItemShelvingRadar (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT iss.itemFk, @@ -59475,80 +59466,86 @@ proc:BEGIN i.size, i.subName producer, i.upToDown, - IFNULL(a.available,0) available, - IFNULL(v.visible - iss.visible,0) dayEndVisible, - IFNULL(v.visible - iss.visible,0) firstNegative, - IFNULL(v.visible - iss.visible,0) itemPlacementVisible, - IFNULL(i.minimum * b.packing,0) itemPlacementSize, + IFNULL(a.available, 0) available, + IFNULL(v.visible - iss.visible, 0) dayEndVisible, + IFNULL(v.visible - iss.visible, 0) firstNegative, + IFNULL(v.visible - iss.visible, 0) itemPlacementVisible, + IFNULL(i.minimum * b.packing, 0) itemPlacementSize, ips.onTheWay, iss.visible itemShelvingStock, - IFNULL(v.visible,0) visible, + IFNULL(v.visible, 0) visible, b.isPickedOff, iss.sectorFk - FROM vn.itemShelvingStock iss - JOIN vn.item i on i.id = iss.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk - LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk - LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 - GROUP BY itemFk - ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - OR iss.sectorFk = vSectorFk; + FROM itemShelvingStock iss + JOIN item i ON i.id = iss.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk + AND lb.warehouse_id = vWarehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN cache.available a ON a.item_id = iss.itemFk + AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk + AND v.calc_id = vCalcVisibleFk + LEFT JOIN ( + SELECT itemFk, SUM(saldo) onTheWay + FROM itemPlacementSupplyList + WHERE saldo > 0 + GROUP BY itemFk + ) ips ON ips.itemFk = i.id + WHERE iss.sectorFk = vSectorFk + OR iss.sectorFk IS NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; - CREATE TEMPORARY TABLE tmp.itemOutTime - SELECT *,SUM(amount) quantity - FROM - (SELECT io.itemFk, - io.quantity amount, - IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, - IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes - FROM itemTicketOut io - JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.itemFk - JOIN vn.ticket t on t.id= io.ticketFk - JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk - JOIN vn.state s ON s.id = ts.stateFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - WHERE st.created > util.VN_CURDATE() - AND st.isChecked - ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk - WHERE t.warehouseFk = vWarehouseFk - AND s.isPicked = 0 - AND NOT io.reserved - AND stPrevious.saleFk IS NULL - AND io.shipped >= util.VN_CURDATE() - AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY - ) sub - GROUP BY itemFk, hours, minutes; + CREATE OR REPLACE TEMPORARY TABLE tmp.itemOutTime + SELECT *, SUM(amount) quantity + FROM ( + SELECT io.itemFk, + io.quantity amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) `hours`, + IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) `minutes` + FROM itemTicketOut `io` + JOIN tItemShelvingRadar isr ON isr.itemFk = io.itemFk + JOIN ticket t ON t.id= io.ticketFk + JOIN ticketState ts ON ts.ticketFk = io.ticketFk + JOIN `state` s ON s.id = ts.stateFk + LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN ( + SELECT DISTINCT saleFk + FROM saleTracking st + WHERE st.created > util.VN_CURDATE() + AND st.isChecked + ) stPrevious ON stPrevious.saleFk = io.saleFk + WHERE t.warehouseFk = vWarehouseFk + AND NOT s.isPicked + AND NOT io.reserved + AND stPrevious.saleFk IS NULL + AND io.shipped >= util.VN_CURDATE() + AND io.shipped < util.VN_CURDATE() + INTERVAL 1 DAY + ) sub + GROUP BY itemFk, `hours`, `minutes`; - INSERT INTO tmp.itemShelvingRadar (itemFk) + INSERT INTO tItemShelvingRadar (itemFk) SELECT itemFk FROM tmp.itemOutTime - ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, - firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), - `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), - `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + firstNegative = IF(firstNegative < 0, firstNegative, firstNegative + quantity), + `hour` = IFNULL(IF(firstNegative > 0 , `hour`, `hours`), 0), + `minute` = IFNULL(IF(firstNegative > 0, `minute`, `minutes`), 0); - UPDATE tmp.itemShelvingRadar isr - JOIN (SELECT s.itemFk, sum(s.quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN ticketLastState tls ON tls.ticketFk = t.id - WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - AND tls.name = 'Prep Camara' - GROUP BY s.itemFk) sub ON sub.itemFk = isr.itemFk + UPDATE tItemShelvingRadar isr + JOIN ( + SELECT s.itemFk, SUM(s.quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketState ts ON ts.ticketFk = t.id + WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) + AND ts.code = 'COOLER_PREPARATION' + GROUP BY s.itemFk + ) sub ON sub.itemFk = isr.itemFk SET isr.dayEndVisible = dayEndVisible + sub.amount, firstNegative = firstNegative + sub.amount; - SELECT * FROM tmp.itemShelvingRadar; + SELECT * FROM tItemShelvingRadar; END IF; - DROP TEMPORARY TABLE tmp.itemShelvingRadar; + DROP TEMPORARY TABLE tItemShelvingRadar; END ;; DELIMITER ; @@ -60470,6 +60467,74 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_getItemDetails` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getItemDetails`( + vBarcodeItem INT, + vShelvingFK VARCHAR(10) +) +BEGIN +/** + * Obtiene el precio y visible de un item + * + * @param vBarcodeItem barcode de artículo + * @param vShelvingFK Ubicación actual del artículo + */ + DECLARE vIsItem BOOL; + DECLARE vBuyFk INT; + DECLARE vWarehouseFk INT; + + SELECT COUNT(*) > 0 INTO vIsItem + FROM item + WHERE id = vBarcodeItem; + + IF vIsItem THEN + SELECT warehouseFk INTO vWarehouseFk + FROM operator + WHERE workerFk = account.myUser_getId(); + + CALL buyUltimate(vWarehouseFk, util.VN_CURDATE()); + + SELECT buyFk INTO vBuyFk + FROM tmp.buyUltimate + WHERE itemFk = vBarcodeItem + AND warehouseFk = vWarehouseFk; + + DELETE FROM tmp.buyUltimate; + ELSE + SELECT vBarcodeItem INTO vBuyFk; + END IF; + + WITH visible AS( + SELECT itemFk, + IFNULL(buyingValue, 0) + + IFNULL(freightValue, 0) + + IFNULL(comissionValue, 0) + + IFNULL(packageValue, 0) itemCost + FROM vn.buy b + WHERE b.id = vBuyFk + ) SELECT v.itemFk, + vShelvingFK, + v.itemCost, + SUM(ish.visible) visible + FROM vn.itemShelving ish + JOIN visible v + WHERE ish.shelvingFK = vShelvingFK COLLATE utf8mb3_general_ci + AND ish.itemFk = v.itemFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelving_getSaleDate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -61131,75 +61196,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTrash` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTrash`( - vItemFk INT, - vWarehouseFk INT, - vQuantity INT, - vIsTrash BOOLEAN) -BEGIN - DECLARE vTicketFk INT; - DECLARE vClientFk INT; - DECLARE vCompanyVnlFk INT DEFAULT 442; - DECLARE vCalc INT; - - SELECT barcodeToItem(vItemFk) INTO vItemFk; - - SELECT IF(vIsTrash, 200, 400) INTO vClientFk; - - SELECT t.id INTO vTicketFk - FROM ticket t - JOIN address a ON a.id=t.addressFk - WHERE t.warehouseFk = vWarehouseFk - AND t.clientFk = vClientFk - AND DATE(t.shipped) = util.VN_CURDATE() - AND a.isDefaultAddress - LIMIT 1; - - CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); - - IF vTicketFk IS NULL THEN - CALL ticket_add( - vClientFk, - util.VN_CURDATE(), - vWarehouseFk, - vCompanyVnlFk, - NULL, - NULL, - NULL, - util.VN_CURDATE(), - account.myUser_getId(), - FALSE, - vTicketFk); - END IF; - - INSERT INTO sale(ticketFk, itemFk, concept, quantity) - SELECT vTicketFk, - vItemFk, - CONCAT(longName,' ',worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)), - vQuantity - FROM item - WHERE id = vItemFk; - - UPDATE cache.visible - SET visible = visible - vQuantity - WHERE calc_id = vCalc - AND item_id = vItemFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemUpdateTag` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -61821,6 +61817,427 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_devalueA2` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `item_devalueA2`( + vSelf INT, + vShelvingFK VARCHAR(10), + vBuyingValue DECIMAL(10,4), + vQuantity INT +) +BEGIN +/** + * Devalua un item modificando su calidad de A1 a A2. + * Si no existe el item A2 lo crea y genera los movimientos de las entradas + * de almacén y shelvings correspondientes + * + * @param vSelf Id de artículo a devaluar + * @param vShelvingFK Ubicación actual del artículo + * @param vBuyingValue Nuevo precio de coste + * @param vQuantity Cantidad del ítem a pasar a A2 + */ + DECLARE vItemA2Fk INT; + DECLARE vLastBuyFk BIGINT; + DECLARE vA1BuyFk INT; + DECLARE vA2BuyFk INT; + DECLARE vTargetEntryFk INT; + DECLARE vTargetEntryDate DATE; + DECLARE vTargetItemShelvingFk BIGINT; + DECLARE vWarehouseFk INT; + DECLARE vCacheFk INT; + DECLARE vLastEntryFk INT; + DECLARE vCurrentVisible INT; + DECLARE vDevalueTravelFk INT; + DECLARE vCurdate DATE; + DECLARE vBuyingValueOriginal DECIMAL(10,4); + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT TRUE FROM item WHERE id = vSelf AND (category <> 'A1' OR category IS NULL)) THEN + CALL util.throw('Item has not category A1'); + END IF; + + SELECT warehouseFk INTO vWarehouseFk + FROM userConfig + WHERE userFk = account.myUser_getId(); + + IF NOT vWarehouseFk OR vWarehouseFk IS NULL THEN + CALL util.throw ('Operator has not a valid warehouse'); + END IF; + + IF vQuantity <= 0 OR vQuantity IS NULL THEN + CALL util.throw ('The quantity is incorrect'); + END IF; + + SELECT util.VN_CURDATE() INTO vCurdate; + + SELECT t.id INTO vDevalueTravelFk + FROM travel t + JOIN travelConfig tc + WHERE t.shipped = vCurdate + AND t.landed = vCurdate + AND t.warehouseInFk = vWarehouseFk + AND t.warehouseOutFk = tc.devalueWarehouseOutFk + AND t.agencyModeFk = tc.devalueAgencyModeFk + LIMIT 1; + + IF NOT vDevalueTravelFk OR vDevalueTravelFk IS NULL THEN + INSERT INTO travel ( + shipped, + landed, + warehouseInFk, + warehouseOutFk, + `ref`, + isReceived, + agencyModeFk) + SELECT vCurdate, + vCurdate, + vWarehouseFk, + tc.devalueWarehouseOutFk, + tc.devalueRef, + TRUE, + tc.devalueAgencyModeFk + FROM travelConfig tc; + SET vDevalueTravelFk = LAST_INSERT_ID(); + END IF; + + SELECT id, DATE(dated) INTO vTargetEntryFk, vTargetEntryDate + FROM `entry` e + WHERE DATE(dated) = vCurdate + AND typeFk = 'devaluation' + AND travelFk = vDevalueTravelFk + ORDER BY created DESC + LIMIT 1; + + CALL buyUltimate(vWarehouseFk, vCurdate); + + SELECT b.entryFk, bu.buyFk,IFNULL(b.buyingValue, 0) INTO vLastEntryFk, vLastBuyFk, vBuyingValueOriginal + FROM tmp.buyUltimate bu + JOIN vn.buy b ON b.id = bu.buyFk + WHERE bu.itemFk = vSelf + AND bu.warehouseFk = vWarehouseFk; + + IF vBuyingValue > vBuyingValueOriginal THEN + CALL util.throw ('Price not valid'); + END IF; + + IF vLastEntryFk IS NULL OR vLastBuyFk IS NULL THEN + CALL util.throw ('The item has not a buy'); + END IF; + + SELECT id,visible INTO vTargetItemShelvingFk, vCurrentVisible + FROM itemShelving + WHERE shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci + AND itemFk = vSelf + LIMIT 1; + + IF vCurrentVisible IS NULL THEN + CALL util.throw ('The shelving has not a visible for this item'); + END IF; + + IF vQuantity > vCurrentVisible THEN + CALL util.throw('Quantity is greater than visible'); + END IF; + + START TRANSACTION; + + IF NOT vTargetEntryFk OR vTargetEntryFk IS NULL + OR NOT vTargetEntryDate <=> vCurdate THEN + INSERT INTO entry( + travelFk, + supplierFk, + dated, + commission, + currencyFk, + companyFk, + clonedFrom, + typeFk + ) + SELECT vDevalueTravelFk, + supplierFk, + vCurdate, + commission, + currencyFk, + companyFk, + vLastEntryFk, + 'devaluation' + FROM entry + WHERE id = vLastEntryFk; + + SET vTargetEntryFk = LAST_INSERT_ID(); + END IF; + + SELECT i.id INTO vItemA2Fk + FROM item i + JOIN ( + SELECT i.id, + i.name, + i.subname, + i.value5, + i.value6, + i.value7, + i.value8, + i.value9, + i.value10, + i.NumberOfItemsPerCask, + i.EmbalageCode, + i.quality + FROM item i + WHERE i.id = vSelf + )i2 ON i2.name <=> i.name + AND i2.subname <=> i.subname + AND i2.value5 <=> i.value5 + AND i2.value6 <=> i.value6 + AND i2.value8 <=> i.value8 + AND i2.value9 <=> i.value9 + AND i2.value10 <=> i.value10 + AND i2.NumberOfItemsPerCask <=> i.NumberOfItemsPerCask + AND i2.EmbalageCode <=> i.EmbalageCode + AND i2.quality <=> i.quality + WHERE i.id <> i2.id + AND i.category = 'A2' + LIMIT 1; + + IF vItemA2Fk IS NULL THEN + INSERT INTO item ( + equivalent, + name, + `size`, + stems, + minPrice, + isToPrint, + family, + box, + category, + originFk, + doPhoto, + image, + inkFk, + intrastatFk, + hasMinPrice, + created, + comment, + typeFk, + generic, + producerFk, + description, + density, + relevancy, + expenseFk, + isActive, + longName, + subName, + minimum, + upToDown, + supplyResponseFk, + hasKgPrice, + isFloramondo, + isFragile, + numberOfItemsPerCask, + embalageCode, + quality, + stemMultiplier, + itemPackingTypeFk, + packingOut, + genericFk, + isLaid, + lastUsed, + weightByPiece, + editorFk, + recycledPlastic, + nonRecycledPlastic) + SELECT equivalent, + name, + `size`, + stems, + minPrice, + isToPrint, + family, + box, + 'A2', + originFk, + doPhoto, + image, + inkFk, + intrastatFk, + hasMinPrice, + created, + comment, + typeFk, + generic, + producerFk, + description, + density, + relevancy, + expenseFk, + isActive, + longName, + subName, + minimum, + upToDown, + supplyResponseFk, + hasKgPrice, + isFloramondo, + isFragile, + numberOfItemsPerCask, + embalageCode, + quality, + stemMultiplier, + itemPackingTypeFk, + packingOut, + genericFk, + isLaid, + lastUsed, + weightByPiece, + editorFk, + recycledPlastic, + nonRecycledPlastic + FROM item + WHERE id = vSelf; + + SET vItemA2Fk = LAST_INSERT_ID(); + + INSERT INTO itemTag (itemFk, tagFk, `value`, intValue, priority, editorFk) + SELECT vItemA2Fk, tagFk, `value`, intValue, priority, editorFk + FROM itemTag + WHERE id = vSelf; + + UPDATE itemTaxCountry itc + JOIN itemTaxCountry itc2 ON itc2.itemFk = vSelf + AND itc2.countryFk = itc.countryFk + SET itc2.taxClassFk = itc.taxClassFk + WHERE itc.id = vItemA2Fk; + + INSERT INTO itemBotanical (itemFk, genusFk, specieFk) + SELECT vItemA2Fk, genusFk, specieFk + FROM itemBotanical + WHERE itemFk = vSelf; + END IF; + + IF vQuantity = vCurrentVisible THEN + DELETE FROM itemShelving + WHERE id = vTargetItemShelvingFk; + ELSE + UPDATE itemShelving + SET visible = vCurrentVisible - vQuantity + WHERE id = vTargetItemShelvingFk; + END IF; + + INSERT INTO buy( + entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk) + SELECT vTargetEntryFk, + itemFk, + - LEAST(vQuantity, vCurrentVisible), + buyingValue, + freightValue, + TRUE, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk + FROM vn.buy + WHERE id = vLastBuyFk + UNION + SELECT vTargetEntryFk, + vItemA2Fk, + vQuantity, + vBuyingValue, + freightValue, + TRUE, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk + FROM vn.buy + WHERE id = vLastBuyFk; + + INSERT IGNORE INTO itemShelving ( + itemFk, + shelvingFk, + visible, + `grouping`, + packing, + packagingFk, + userFk, + isChecked) + SELECT vItemA2Fk, + shelvingFk, + vQuantity , + `grouping`, + packing, + packagingFk, + account.myUser_getId(), + isChecked + FROM itemShelving + WHERE itemFK = vSelf + AND shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci + ON DUPLICATE KEY UPDATE + visible = vQuantity + VALUES(visible); + + COMMIT; + CALL cache.visible_refresh(vCacheFk, TRUE, vWarehouseFk); + CALL cache.available_refresh(vCacheFk, TRUE, vWarehouseFk, vCurdate); + CALL buy_recalcPricesByBuy(vA2BuyFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `item_getAtp` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -61900,7 +62317,7 @@ BEGIN * @vItemFk item a buscar * @vWarehouseFk almacen donde buscar * @vDate Si la fecha es null, muestra el histórico desde el inventario. - * Si la fecha no es null, muestra histórico desde la fecha pasada. + * Si la fecha no es null, muestra histórico desde la fecha de vDate. */ DECLARE vDateInventory DATETIME; @@ -61931,117 +62348,154 @@ BEGIN inventorySupplierFk INT(10) ); - INSERT INTO tItemDiary - SELECT tr.landed shipped, - b.quantity `in`, - NULL `out`, - st.alertLevel , - st.name stateName, - s.name `name`, - e.invoiceNumber reference, - e.id origin, - s.id clientFk, - IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked, - FALSE isTicket, - b.id lineFk, - NULL `order`, - NULL clientType, - NULL claimFk, - ec.inventorySupplierFk - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() - OR (util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', - 'FREE') - JOIN entryConfig ec - WHERE tr.landed >= vDateInventory - AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) - AND b.itemFk = vItemFk - AND e.isExcludedFromAvailable = FALSE - AND e.isRaid = FALSE - UNION ALL - SELECT tr.shipped, - NULL, - b.quantity, - st.alertLevel, - st.name, - s.name, - e.invoiceNumber, - e.id, - s.id, - IF(st.`code` = 'DELIVERED' , TRUE, FALSE), - FALSE, - b.id, - NULL, - NULL, - NULL, - ec.inventorySupplierFk - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN warehouse w ON w.id = tr.warehouseOutFk - JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() + INSERT INTO tItemDiary + WITH entriesIn AS ( + SELECT tr.landed shipped, + b.quantity `in`, + NULL `out`, + st.alertLevel , + st.name stateName, + s.name `name`, + e.invoiceNumber reference, + e.id origin, + s.id clientFk, + IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked, + FALSE isTicket, + b.id lineFk, + NULL `order`, + NULL clientType, + NULL claimFk, + ec.inventorySupplierFk + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + OR (util.VN_CURDATE() AND tr.isReceived), + 'DELIVERED', + 'FREE') + JOIN vn.entryConfig ec + WHERE tr.landed >= vDateInventory + AND vWarehouseFk = tr.warehouseInFk + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND b.itemFk = vItemFk + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ), entriesOut AS ( + SELECT tr.shipped, + NULL, + b.quantity, + st.alertLevel, + st.name stateName, + s.name , + e.invoiceNumber, + e.id entryFk, + s.id supplierFk, + IF(st.`code` = 'DELIVERED' , TRUE, FALSE), + FALSE isTicket, + b.id, + NULL `order`, + NULL clientType, + NULL claimFk, + ec.inventorySupplierFk + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.warehouse w ON w.id = tr.warehouseOutFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', - 'FREE') - JOIN entryConfig ec - WHERE tr.shipped >= vDateInventory - AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) - AND b.itemFk = vItemFk - AND e.isExcludedFromAvailable = FALSE - AND w.isFeedStock = FALSE - AND e.isRaid = FALSE - UNION ALL - SELECT DATE(t.shipped), - NULL, - s.quantity, - st2.alertLevel, - st2.name, - t.nickname, - t.refFk, - t.id, - t.clientFk, - stk.id, - TRUE, - s.id, - st.`order`, - c.typeFk, - cb.claimFk, - NULL - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - LEFT JOIN state st ON st.`code` = ts.`code` - JOIN client c ON c.id = t.clientFk - JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', - IF (t.shipped > util.dayEnd(util.VN_CURDATE()), - 'FREE', - IFNULL(ts.code, 'FREE'))) - LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' - LEFT JOIN saleTracking stk ON stk.saleFk = s.id - AND stk.stateFk = stPrep.id - LEFT JOIN claimBeginning cb ON s.id = cb.saleFk - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemFk - AND vWarehouseFk =t.warehouseFk - ORDER BY shipped, - (inventorySupplierFk = clientFk) DESC, - alertLevel DESC, - isTicket, - `order` DESC, - isPicked DESC, - `in` DESC, - `out` DESC; + 'DELIVERED', + 'FREE') + JOIN vn.entryConfig ec + WHERE tr.shipped >= vDateInventory + AND vWarehouseFk = tr.warehouseOutFk + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND b.itemFk = vItemFk + AND NOT e.isExcludedFromAvailable + AND NOT w.isFeedStock + AND NOT e.isRaid + ), sales AS ( + SELECT DATE(t.shipped) shipped, + s.quantity, + st2.alertLevel, + st2.name, + t.nickname, + t.refFk, + t.id ticketFk, + t.clientFk, + s.id saleFk, + st.`order`, + c.typeFk, + cb.claimFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + LEFT JOIN vn.state st ON st.`code` = ts.`code` + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), + 'DELIVERED', + IF (t.shipped > util.dayEnd(util.VN_CURDATE()), + 'FREE', + IFNULL(ts.code, 'FREE'))) + LEFT JOIN vn.claimBeginning cb ON s.id = cb.saleFk + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemFk + AND vWarehouseFk = t.warehouseFk + ),sale AS ( + SELECT s.shipped, + NULL `in`, + s.quantity, + s.alertLevel, + s.name, + s.nickname, + s.refFk, + s.ticketFk, + s.clientFk, + IF(stk.saleFk, TRUE, NULL), + TRUE, + s.saleFk, + s.`order`, + s.typeFk, + s.claimFk, + NULL + FROM sales s + LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED' + LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk + AND stk.stateFk = stPrep.id + GROUP BY s.saleFk + ) SELECT shipped, + `in`, + `out`, + alertLevel, + stateName, + `name`, + reference, + origin, + clientFk, + isPicked, + isTicket, + lineFk, + `order`, + clientType, + claimFk, + inventorySupplierFk + FROM entriesIn + UNION ALL + SELECT * FROM entriesOut + UNION ALL + SELECT * FROM sale + ORDER BY shipped, + (inventorySupplierFk = clientFk) DESC, + alertLevel DESC, + isTicket, + `order` DESC, + isPicked DESC, + `in` DESC, + `out` DESC; IF vDate IS NULL THEN - + SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; @@ -62111,7 +62565,7 @@ BEGIN FROM tItemDiary WHERE shipped >= vDate; END IF; - + DROP TEMPORARY TABLE tItemDiary; END ;; DELIMITER ; @@ -62435,6 +62889,9 @@ BEGIN CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); + -- Añadido temporalmente para que no se cuelgue la db + SET vShowType = TRUE; + WITH itemTags AS ( SELECT i.id, typeFk, @@ -63390,7 +63847,15 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_doCompensation`(vDated DATE, vCompensationAccount VARCHAR(10) , vBankFk VARCHAR(10), vConcept VARCHAR(255), vAmount DECIMAL(10,2), vCompanyFk INT, vOriginalAccount VARCHAR(10)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_doCompensation`( + vDated DATE, + vCompensationAccount VARCHAR(10), + vBankFk VARCHAR(10), + vConcept VARCHAR(255), + vAmount DECIMAL(10,2), + vCompanyFk INT, + vOriginalAccount VARCHAR(10) +) BEGIN /** * Compensa un pago o un recibo insertando en contabilidad @@ -63400,29 +63865,31 @@ BEGIN * @param vBankFk banco de la compensacion * @param vConcept descripcion * @param vAmount cantidad que se compensa - * @param vCompany empresa + * @param vCompanyFk empresa * @param vOriginalAccount cuenta contable desde la cual se compensa * - */ + */ DECLARE vNewBookEntry INT; - DECLARE vIsClientCompensation INT; + DECLARE vIsClientCompensation INT; DECLARE vClientFk INT; - DECLARE vSupplierFk INT; - DECLARE vIsOriginalAClient BOOL; - DECLARE vPayMethodCompensation INT; - - CALL ledger_next(vNewBookEntry); + DECLARE vSupplierFk INT; + DECLARE vIsOriginalAClient BOOL; + DECLARE vPayMethodCompensation INT; - SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci; + CALL ledger_next(YEAR(vDated), vNewBookEntry); + + SELECT COUNT(id) INTO vIsOriginalAClient + FROM client + WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci; SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation FROM client WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci; - + SET @vAmount1:= 0.0; SET @vAmount2:= 0.0; - INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) + INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) VALUES ( vNewBookEntry, vDated, vOriginalAccount, @@ -63440,31 +63907,52 @@ BEGIN ), vCompanyFk ), - ( vNewBookEntry, - vDated, - vCompensationAccount, - vOriginalAccount, - vConcept, - @vAmount2, + ( vNewBookEntry, + vDated, + vCompensationAccount, + vOriginalAccount, + vConcept, + @vAmount2, @vAmount1, - vCompanyFk); - - IF vIsClientCompensation THEN - IF vIsOriginalAClient THEN - SET vAmount = -vAmount; - END IF; - INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) - VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE); - ELSE - IF NOT vIsOriginalAClient THEN - SET vAmount = -vAmount; - END IF; - SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; - SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation'; - - INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated) - VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE); - END IF; + vCompanyFk); + + IF vIsClientCompensation THEN + IF vIsOriginalAClient THEN + SET vAmount = -vAmount; + END IF; + + INSERT INTO receipt + SET invoiceFk = vConcept, + amountPaid = vAmount, + payed = vDated, + bankFk = vBankFk, + companyFk = vCompanyFk, + clientFk = vClientFk, + isConciliate = TRUE; + ELSE + IF NOT vIsOriginalAClient THEN + SET vAmount = -vAmount; + END IF; + + SELECT id INTO vSupplierFk + FROM supplier + WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; + + SELECT id INTO vPayMethodCompensation + FROM payMethod + WHERE `code` = 'compensation'; + + INSERT INTO payment + SET received = vDated, + dueDated = vDated, + supplierFk = vSupplierFk, + amount = vAmount, + bankFk = vBankFk, + payMethodFk = vPayMethodCompensation, + concept = vConcept, + companyFk = vCompanyFk, + isConciliated = TRUE; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63481,12 +63969,58 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`(OUT vNewBookEntry INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`( + IN vFiscalYear INT, + OUT vLastBookEntry INT +) BEGIN - - UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1); - SET vNewBookEntry = LAST_INSERT_ID(); - + DECLARE vHasStartTransaction BOOLEAN; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + + IF vHasStartTransaction THEN + ROLLBACK TO sp; + RESIGNAL; + ELSE + ROLLBACK; + CALL util.throw ('It has not been possible to generate a new ledger'); + END IF; + END; + + IF vFiscalYear IS NULL THEN + CALL util.throw('Fiscal year is required'); + END IF; + + SELECT @@in_transaction INTO vHasStartTransaction; + + IF NOT vHasStartTransaction THEN + START TRANSACTION; + ELSE + SAVEPOINT sp; + END IF; + + SELECT bookEntry + 1 INTO vLastBookEntry + FROM ledgerCompany + WHERE fiscalYear = vFiscalYear + FOR UPDATE; + + IF vLastBookEntry IS NULL THEN + INSERT INTO ledgerCompany + SET fiscalYear = vFiscalYear, + bookEntry = 1; + SET vLastBookEntry = 1; + END IF; + + UPDATE ledgerCompany + SET bookEntry = vLastBookEntry + WHERE fiscalYear = vFiscalYear; + + IF vHasStartTransaction THEN + RELEASE SAVEPOINT sp; + ELSE + COMMIT; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64447,140 +64981,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `packageInvoicing` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( - IN vClient INT, - IN vDate DATE, - IN vCompany INT, - IN vIsAllInvoiceable BOOLEAN, - OUT vNewTicket INT(11) - ) -BEGIN - - DECLARE vGraceDays INT; - DECLARE vDateStart DATE DEFAULT '2017-11-21'; - DECLARE vIsInvoiceable BOOLEAN; - DECLARE vWarehouse INT DEFAULT 13; - DECLARE vComponentCost INT DEFAULT 28; - DECLARE vGraceDate DATE; - DECLARE vDateEnd DATE; - - SET vGraceDays = IF(vIsAllInvoiceable ,0, 30); - SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: - 3240 MADEFLOR - 992 JAVIER FELIU - 4 TONI VENDRELL - */ - - IF vClient IN (992, 3240, 4) THEN - - SET vGraceDays = 365; - - END IF; - /* Fin clientes especiales */ - - SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY); - - DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; - - CREATE TEMPORARY TABLE tmp.packageToInvoice - SELECT p.itemFk, - tp.packagingFk, - IF(tp.quantity < 0 OR t.shipped < vGraceDate, tp.quantity, 0) quantity, - tp.ticketFk, - p.price - FROM ticketPackaging tp - JOIN packaging p ON p.id = tp.packagingFk - JOIN ticket t ON t.id = tp.ticketFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND t.clientFk = vClient; - - DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoicePositives; - - CREATE TEMPORARY TABLE tmp.packageToInvoicePositives - SELECT itemFk, sum(quantity) as totalQuantity - FROM tmp.packageToInvoice - GROUP BY itemFk - HAVING totalQuantity > 0; - - SELECT COUNT(*) - INTO vIsInvoiceable - FROM tmp.packageToInvoicePositives; - - IF vIsInvoiceable THEN - - CALL ticket_add(vClient, - vDateEnd, - vWarehouse, - vCompany, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), - TRUE, - vNewTicket); - - INSERT INTO ticketPackaging( - ticketFk, - packagingFk, - quantity, - pvp) - SELECT vNewTicket, - pti.packagingFk, - - SUM(pti.quantity) AS totalQuantity, - pti.price - FROM tmp.packageToInvoice pti - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL - OR vIsAllInvoiceable - GROUP BY packagingFk - HAVING totalQuantity; - - INSERT INTO sale( - ticketFk, - itemFk, - concept, - quantity, - price - ) - SELECT vNewTicket, - pti.itemFk, - i.name as concept, - sum(pti.quantity) as totalQuantity, - pti.price - FROM tmp.packageToInvoice pti - JOIN item i ON i.id = pti.itemFk - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL - OR vIsAllInvoiceable - GROUP BY pti.itemFk - HAVING totalQuantity; - - INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT id, vComponentCost, price - FROM sale - WHERE ticketFk = vNewTicket; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `packingListSwitch` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -66156,7 +66556,7 @@ BEGIN CONCAT(tc.collectionFk, ' ', LEFT(cc.code, 4)) color, CONCAT(tc.collectionFk, ' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.level) levelV, tc.ticketFk, - LEFT(COALESCE(et.description, zo.name, am.name),12) agencyDescription, + LEFT(COALESCE(rs.description, zo.name, am.name),12) agencyDescription, am.name, t.clientFk, CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5, 2)), 'm³') m3 , @@ -66183,7 +66583,7 @@ BEGIN LEFT JOIN ticketTrolley tt ON tt.ticket = t.id LEFT JOIN zone zo ON t.zoneFk = zo.id LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN expeditionTruck et ON et.id = rm.expeditionTruckFk + LEFT JOIN roadmapStop rs ON rs.id = rm.expeditionTruckFk WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) GROUP BY t.id ORDER BY cc.code; @@ -66485,8 +66885,8 @@ BEGIN SET rm.m3boxes = sub.m3boxes; UPDATE routesMonitor rm - JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk - SET rm.etd = et.eta; + JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + SET rm.etd = rs.eta; DROP TEMPORARY TABLE tmp.routesMonitor; END ;; @@ -67971,7 +68371,7 @@ BEGIN ticketFk INT(11), saleFk INT(11), isFreezed INTEGER(1) DEFAULT 0, - risk DECIMAL(10,2) DEFAULT 0, + risk DECIMAL(10,1) DEFAULT 0, hasHighRisk TINYINT(1) DEFAULT 0, hasTicketRequest INTEGER(1) DEFAULT 0, itemShortage VARCHAR(255), @@ -67981,6 +68381,7 @@ BEGIN hasComponentLack INTEGER(1), hasRounding VARCHAR(255), isTooLittle BOOL DEFAULT FALSE, + isVip BOOL DEFAULT FALSE, PRIMARY KEY (ticketFk, saleFk) ) ENGINE = MEMORY; @@ -68016,6 +68417,14 @@ BEGIN JOIN volumeConfig vc WHERE sub.litros < vc.minTicketVolume AND sub.totalWithoutVat < vc.minTicketValue; + + -- VIP + INSERT INTO tmp.sale_problems(ticketFk, isVip) + SELECT DISTINCT tl.ticketFk, TRUE + FROM tmp.ticket_list tl + JOIN client c ON c.id = tl.clientFk + WHERE c.businessTypeFk = 'VIP' + ON DUPLICATE KEY UPDATE isVip = TRUE; -- Faltan componentes INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk) @@ -68587,6 +68996,160 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_setProblem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_setProblem`( + vProblemCode VARCHAR(25) +) +BEGIN +/** + * Update column sale.problem with a problem code + * @param vProblemCode Code to set or unset + * @table tmp.sale(saleFk, hasProblem) + */ + UPDATE sale s + JOIN tmp.sale ts ON ts.saleFk = s.id + SET s.problem = CONCAT( + IF(ts.hasProblem, + CONCAT(s.problem, ',', vProblemCode), + REPLACE(s.problem, vProblemCode , ''))); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_setProblemComponentLack` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_setProblemComponentLack`( + vSelf INT +) +BEGIN +/** + * Update the problems for sales lines that have or no longer have problems with components, + * verify whether all mandatory components are present or not + * + * @param vSelf Id del sale + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT vSelf saleFk, sale_hasComponentLack(vSelf) hasProblem; + + CALL sale_setProblem('hasComponentLack'); + + DROP TEMPORARY TABLE tmp.sale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_setProblemComponentLackByComponent` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_setProblemComponentLackByComponent`( + vComponentFk INT +) +BEGIN +/** + * Update the issues for sales lines that have or no longer have problems with components, verify + * whether all mandatory components are present or not resulting from changes in the table vn.component + * + * @param vComponentFk Id component + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT saleFk, sale_hasComponentLack(saleFk)hasProblem + FROM ( + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + WHERE t.shipped >= util.midnight() + AND (vComponentFk IS NULL OR sc.componentFk = vComponentFk) + GROUP BY s.id) sub; + + CALL sale_setProblem('hasComponentLack'); + + DROP TEMPORARY TABLE tmp.sale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_setProblemRounding` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_setProblemRounding`( + vSelf INT +) +BEGIN +/** + * Update the rounding problem for a sales line + * @param vSelf Id sale + */ + DECLARE vItemFk INT; + DECLARE vWarehouseFk INT; + DECLARE vShipped DATE; + DECLARE vQuantity INT; + + SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity + INTO vItemFk, vWarehouseFk, vShipped, vQuantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE s.id = vSelf; + + CALL buyUltimate(vWarehouseFk, vShipped); + + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem + FROM tmp.buyUltimate bu + JOIN buy b ON b.id = bu.buyFk + WHERE bu.itemFk = vItemFk; + + CALL sale_setProblem('hasRounding'); + + DROP TEMPORARY TABLE tmp.sale; + DROP TEMPORARY TABLE tmp.buyUltimate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `sectorCollectionSaleGroup_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -69418,7 +69981,7 @@ BEGIN INSERT INTO stockBuyed(buyed, dated, description) SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), vDated, - IF(c.code = 'ES', p.name, c.country) destiny + IF(c.code = 'ES', p.name, c.name) destiny FROM itemTicketOut ito JOIN ticket t ON t.id = ito.ticketFk JOIN `address` a ON a.id = t.addressFk @@ -69702,7 +70265,7 @@ BEGIN itemFk, longName, supplier, - entryFk, + CONCAT('E',entryFk) entryFk, landed, `in`, `out`, @@ -69716,16 +70279,98 @@ BEGIN itemFk, longName, supplier, - 'previous', + 'E previous', vFromDated, SUM(`in`), SUM(`out`), NULL, - buyingValue + AVG(buyingValue) FROM supplierPackaging WHERE supplierFk = vSupplierFk AND landed < vFromDated GROUP BY itemFk + UNION ALL + SELECT vSupplierFk, + s.itemFk, + i.longName, + c.name, + CONCAT('T',s.ticketFk), + DATE(t.shipped), + -LEAST(s.quantity,0) `in`, + GREATEST(s.quantity,0) `out`, + t.warehouseFk, + s.price * (100 - s.discount) / 100 + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN packaging p ON p.itemFk = i.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped >= vFromDated + AND p.isPackageReturnable + UNION ALL + SELECT vSupplierFk, + s.itemFk, + i.longName, + c.name, + 'T previous', + vFromDated, + SUM(-LEAST(s.quantity,0)) `in`, + SUM(GREATEST(s.quantity,0)) `out`, + NULL, + AVG(s.price * (100 - s.discount) / 100) + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN packaging p ON p.itemFk = i.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped < vFromDated + AND p.isPackageReturnable + GROUP BY s.itemFk + UNION ALL + SELECT vSupplierFk, + p.itemFk, + i.longName, + c.name, + CONCAT('TP',tp.ticketFk), + DATE(t.shipped), + -LEAST(tp.quantity,0) `in`, + GREATEST(tp.quantity,0) `out`, + t.warehouseFk, + 0 + FROM ticketPackaging tp + JOIN packaging p ON p.id = tp.packagingFk + JOIN item i ON i.id = p.itemFk + JOIN ticket t ON t.id = tp.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped >= vFromDated + AND p.isPackageReturnable + UNION ALL + SELECT vSupplierFk, + p.itemFk, + i.longName, + c.name, + 'TP previous', + vFromDated, + SUM(-LEAST(tp.quantity,0)) `in`, + SUM(GREATEST(tp.quantity,0)) `out`, + NULL, + 0 + FROM ticketPackaging tp + JOIN packaging p ON p.id = tp.packagingFk + JOIN item i ON i.id = p.itemFk + JOIN ticket t ON t.id = tp.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped >= vFromDated + AND p.isPackageReturnable + GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub WHERE `out` OR `in`; @@ -69736,8 +70381,8 @@ BEGIN supplier, entryFk, landed, - `in`, - `out`, + CAST(`in` AS DECIMAL(10,0)) `in`, + CAST(`out` AS DECIMAL(10,0)) `out`, warehouse, buyingValue, balance @@ -71174,37 +71819,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketRefund_beforeUpsert` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRefund_beforeUpsert`(vRefundTicketFk INT, vOriginalTicketFk INT) -BEGIN - DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; - - IF vRefundTicketFk = vOriginalTicketFk THEN - CALL util.throw('Original ticket and refund ticket has same id'); - END IF; - - SELECT COUNT(*) INTO vAlreadyExists - FROM ticketRefund - WHERE refundTicketFk = vOriginalTicketFk; - - IF vAlreadyExists > 0 THEN - CALL util.throw('This ticket is already a refund'); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketStateToday_setState` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -72821,7 +73435,7 @@ BEGIN * * @param vSelf El id del ticket */ - DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; + DECLARE vCmrFk INT; SELECT cmrFk INTO vCmrFk FROM ticket WHERE id = vSelf; @@ -72858,8 +73472,6 @@ BEGIN AND t.id = vSelf GROUP BY t.id; - START TRANSACTION; - IF vCmrFk THEN UPDATE cmr c JOIN tTicket t @@ -72871,9 +73483,7 @@ BEGIN c.supplierFk = t.supplierFk, c.ead = t.landed WHERE id = vCmrFk; - ELSE - SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; - + ELSE INSERT INTO cmr ( senderInstruccions, truckPlate, @@ -72884,17 +73494,14 @@ BEGIN ead ) SELECT * FROM tTicket; - - SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; - IF vPreviousCmrFk <> vCurrentCmrFk THEN + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN UPDATE ticket - SET cmrFk = vCurrentCmrFk + SET cmrFk = LAST_INSERT_ID() WHERE id = vSelf; END IF; END IF; - COMMIT; DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; @@ -73146,6 +73753,7 @@ BEGIN MAX(itemDelay) itemDelay, MAX(hasRounding) hasRounding, MAX(itemLost) itemLost, + MAX(isVip) isVip, 0 totalProblems FROM tmp.sale_problems GROUP BY ticketFk; @@ -73161,7 +73769,8 @@ BEGIN (tp.isTooLittle) + (tp.itemLost) + (tp.hasRounding) + - (tp.itemShortage) + (tp.itemShortage) + + (tp.isVip) ); DROP TEMPORARY TABLE tmp.sale_problems; @@ -73998,6 +74607,425 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblem`( + vProblemCode VARCHAR(25) +) +BEGIN +/** + * Update column ticket.problem with a problem code + * + * @param vProblemCode Code to set or unset + * @table tmp.ticket(ticketFk, hasProblem) + */ + UPDATE ticket t + JOIN tmp.ticket tt ON tt.ticketFk = t.id + SET t.problem = CONCAT( + IF(tt.hasProblem, + CONCAT(problem, ',', vProblemCode), + REPLACE(problem, vProblemCode , ''))); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemFreeze` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemFreeze`( + vClientFk INT +) +BEGIN +/** + * Update the problem of tickets whose client is frozen or unfrozen + * + * @param vClientFk Id Cliente, if NULL all clients + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + (INDEX(ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk, FALSE hasProblem + FROM ticket t + WHERE t.shipped >= util.midnight() + AND (vClientFk IS NULL OR t.clientFk = vClientFk); + + UPDATE tmp.ticket t + JOIN ticket ti ON ti.id = t.ticketFk + JOIN client c ON c.id = ti.clientFk + SET t.hasProblem = TRUE + WHERE c.isFreezed; + + CALL ticket_setProblem('isFreezed'); + + DROP TEMPORARY TABLE tmp.ticket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemRequest` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemRequest`( + vSelf INT +) +BEGIN +/** + * Update the problems of tickets that have a pending ticketRequest or no longer have it + * + * @param vSelf Id ticket, if NULL ALL tickets + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + (INDEX(ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk, FALSE hasProblem + FROM ticket t + WHERE t.shipped >= util.midnight() + AND (vSelf IS NULL OR t.id = vSelf); + + UPDATE tmp.ticket t + JOIN ticketRequest tr ON tr.ticketFk = t.ticketFk + SET t.hasProblem = TRUE + WHERE tr.isOK IS NULL; + + CALL ticket_setProblem('hasTicketRequest'); + + DROP TEMPORARY TABLE tmp.ticket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemRisk` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemRisk`( + vSelf INT +) +BEGIN +/** + * Update the risk problem for a specific ticket + * + * @param vSelf Id ticket + */ + DECLARE vHasRisk BOOL; + DECLARE vHasHighRisk BOOL; + + SELECT t.risk > (c.credit + 10), ((t.risk - cc.riskTolerance) > (c.credit + 10)) + INTO vHasRisk, vHasHighRisk + FROM client c + JOIN ticket t ON t.clientFk = c.id + JOIN clientConfig cc + WHERE t.id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + SELECT vSelf ticketFk, vHasRisk hasProblem; + + CALL ticket_setProblem('hasRisk'); + + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + SELECT vSelf ticketFk, vHasHighRisk hasProblem; + + CALL ticket_setProblem('hasHighRisk'); + + DROP TEMPORARY TABLE tmp.ticket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemRounding` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemRounding`( + vSelf INT +) +BEGIN +/** + * Update the rounding problem for the sales lines of a ticket + * + * @param vSelf Id de ticket + */ + DECLARE vWarehouseFk INT; + DECLARE vDated DATE; + + SELECT warehouseFk, shipped + INTO vWarehouseFk, vDated + FROM ticket + WHERE id = vSelf; + + CALL buyUltimate(vWarehouseFk, vDated); + + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + SELECT s.id saleFk , MOD(s.quantity, b.`grouping`) hasProblem + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + JOIN buy b ON b.id = bu.buyFk + WHERE t.id = vSelf; + + CALL sale_setProblem('hasRounding'); + + DROP TEMPORARY TABLE tmp.sale; + DROP TEMPORARY TABLE tmp.buyUltimate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemTaxDataChecked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemTaxDataChecked`(vClientFk INT) +BEGIN +/** + * Update the problem of tickets, depending on whether + * the client taxDataCheched is verified or not + * + * @param vClientFk Id cliente, if NULL all clients + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + (INDEX(ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem + FROM ticket t + JOIN client c ON c.id = t.clientFk + WHERE t.shipped >= util.midnight() + AND (c.id = vClientFk OR vClientFk IS NULL); + + CALL ticket_setProblem('isTaxDataChecked'); + + DROP TEMPORARY TABLE tmp.ticket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemTooLittle` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemTooLittle`( + vSelf INT +) +BEGIN +/** + * Update the problems when the ticket is too small or is no longer so + * + * @param vSelf Id del ticket + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + (INDEX(ticketFk)) + ENGINE = MEMORY + SELECT vSelf ticketFk, ticket_isTooLittle(vSelf) hasProblem; + + CALL ticket_setProblem('isTooLittle'); + + DROP TEMPORARY TABLE tmp.ticket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setProblemTooLittleItemCost` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setProblemTooLittleItemCost`( + vItemFk INT +) +BEGIN +/** + * Update the problems when the ticket is too small or is no longer so, + * derived from changes in the itemCost table + * + * @param vItemFk Id del item, NULL ALL items + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + (INDEX(ticketFk)) + ENGINE = MEMORY + WITH tickets AS( + SELECT t.id ticketFk + FROM vn.ticket t + LEFT JOIN vn.sale s ON s.ticketFk = t.id + WHERE t.shipped >= util.midnight() + AND (s.itemFk = vItemFk OR vItemFk IS NULL) + GROUP BY t.id + )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem + FROM tickets; + + CALL ticket_setProblem('isTooLittle'); + + DROP TEMPORARY TABLE tmp.ticket; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_setRisk` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setRisk`( + vClientFk INT) +BEGIN +/** + * Update the risk for a client with pending tickets + * + * @param vClientFk Id cliente + */ + DECLARE vHasDebt BOOL; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` + WHERE id = vClientFk + AND typeFk = 'normal'; + + IF vHasDebt THEN + + CREATE OR REPLACE TEMPORARY TABLE tTicketRisk + (KEY (ticketFk)) + ENGINE = MEMORY + WITH ticket AS( + SELECT id ticketFk, companyFk, DATE(shipped) dated + FROM vn.ticket t + WHERE clientFk = vClientFk + AND refFk IS NULL + AND NOT isDeleted + AND totalWithoutVat <> 0 + ), dated AS( + SELECT t.companyFk, MIN(DATE(t.dated) - INTERVAL cc.riskScope MONTH) started, + MAX(DATE(t.dated)) ended + FROM ticket t + JOIN vn.clientConfig cc + GROUP BY t.companyFk + ), balance AS( + SELECT SUM(amount)amount, companyFk + FROM ( + SELECT amount, companyFk + FROM vn.clientRisk + WHERE clientFk = vClientFk + UNION ALL + SELECT -(SUM(amount) / 100) amount, tm.companyFk + FROM hedera.tpvTransaction t + JOIN hedera.tpvMerchant tm ON t.id = t.merchantFk + WHERE clientFk = vClientFk + AND receiptFk IS NULL + AND status = 'ok' + ) sub + WHERE companyFk + GROUP BY companyFk + ), uninvoiced AS( + SELECT t.companyFk, DATE(t.shipped) dated, SUM(IFNULL(t.totalWithVat, 0)) amount + FROM vn.ticket t + JOIN dated d + WHERE t.clientFk = vClientFk + AND t.refFk IS NULL + AND t.shipped BETWEEN d.started AND d.ended + GROUP BY t.companyFk, DATE(t.shipped) + ), receipt AS( + SELECT companyFk,DATE(payed) dated, SUM(amountPaid) amount + FROM vn.receipt + WHERE clientFk = vClientFk + AND payed > util.VN_CURDATE() + GROUP BY companyFk, DATE(payed) + ), risk AS( + SELECT b.companyFk, + ui.dated, + SUM(ui.amount) OVER (PARTITION BY b.companyFk ORDER BY ui.dated ) + + b.amount + + SUM(IFNULL(r.amount, 0)) amount + FROM balance b + JOIN uninvoiced ui ON ui.companyFk = b.companyFk + LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk + GROUP BY b.companyFk, ui.dated + ) + SELECT ti.ticketFk, r.amount + FROM ticket ti + JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk; + + UPDATE ticket t + JOIN tTicketRisk tr ON tr.ticketFk = t.id + SET t.risk = tr.amount; + + DROP TEMPORARY TABLE tTicketRisk; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_setState` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -74385,6 +75413,92 @@ BEGIN GROUP BY ib.ediBotanic, o.code; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `till_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 = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `till_new`( + vClient INT, + vBank INT, + vAmount DOUBLE, + vConcept VARCHAR(25), + vDated DATE, + vSerie CHAR(1), + vBatch TINYINT, + vNumber INT, + vCompany SMALLINT, + vWorker INT +) +BEGIN + DECLARE vAccount VARCHAR(12); + DECLARE vSubaccount VARCHAR(12); + DECLARE vAsiento INT DEFAULT NULL; + + -- Inserta el registro en cajas + INSERT INTO till + SET + workerFk = vWorker, + bankFk = vBank, + `in` = vAmount, + concept = vConcept, + dated = vDated, + serie = vSerie, + isAccountable = vBatch, + `number` = vNumber, + companyFk = vCompany; + + -- Inserta los asientos contables + SELECT account INTO vAccount + FROM accounting WHERE id = vBank; + + SELECT accountingAccount INTO vSubaccount + FROM `client` WHERE id = vClient; + + CALL xdiario_new( + vAsiento, + vDated, + vAccount, + vSubaccount, + vConcept, + vAmount, + 0, + 0, + NULL, -- Serie + NULL, -- Factura + NULL, -- IVA + NULL, -- Recargo + FALSE, -- Auxiliar + vCompany, + vAsiento); + + CALL xdiario_new( + vAsiento, + vDated, + vSubaccount, + vAccount, + vConcept, + 0, + vAmount, + 0, + NULL, -- Serie + NULL, -- Factura + NULL, -- IVA + NULL, -- Recargo + FALSE, -- Auxiliar + vCompany, + vAsiento); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76533,6 +77647,10 @@ mainLabel:BEGIN UPDATE `client` c SET c.salesPersonFk = null WHERE c.salesPersonFk = vUserId; + + UPDATE locker l + SET l.workerFk = NULL + WHERE l.workerFk = vUserId; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78369,6 +79487,43 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `worker_checkMultipleDevice` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_checkMultipleDevice`( + vSelf INT +) +BEGIN +/** + * Verify if a worker has multiple assigned devices, + * except for freelancers. + * + * @param vUserFk worker id. + */ + DECLARE vHasPda BOOLEAN; + DECLARE vIsFreelance BOOLEAN; + DECLARE vMaxDevicesPerUser INT; + + SELECT COUNT(*) INTO vHasPda FROM deviceProductionUser WHERE userFk = vSelf; + SELECT IFNULL(isFreelance, FALSE) INTO vIsFreelance FROM worker WHERE id = vSelf; + SELECT IFNULL(maxDevicesPerUser, FALSE) INTO vMaxDevicesPerUser FROM deviceProductionConfig LIMIT 1; + + IF NOT vIsFreelance AND vHasPda > vMaxDevicesPerUser THEN + CALL util.throw('You can only have one PDA'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `worker_getFromHasMistake` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -78477,7 +79632,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateBalance`(vSelfFk INT(11), vCredit DECIMAL(10,2), vDebit DECIMAL(10,2)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateBalance`(vSelf INT(11), vCredit DECIMAL(10,2), vDebit DECIMAL(10,2)) BEGIN /** * Actualiza la columna balance de worker. @@ -78486,7 +79641,7 @@ BEGIN */ UPDATE worker SET balance = IFNULL(balance, 0) + IFNULL(vCredit, 0) - IFNULL(vDebit, 0) - WHERE id = vSelfFk; + WHERE id = vSelf; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78797,6 +79952,62 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `xdiario_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 = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `xdiario_new`( + vBookNumber INT, + vDated DATE, + vSubaccount VARCHAR(12), + vAccount VARCHAR(12), + vConcept VARCHAR(25), + vDebit DOUBLE, + vCredit DOUBLE, + vEuro DOUBLE, + vSerie CHAR(1), + vInvoice VARCHAR(8), + vVat DOUBLE, + vRe DOUBLE, + vAux TINYINT, + vCompanyFk INT, + OUT vNewBookNumber INT +) +BEGIN + IF vBookNumber IS NULL THEN + CALL ledger_next(YEAR(vDated), vBookNumber); + END IF; + + INSERT INTO XDiario + SET ASIEN = vBookNumber, + FECHA = vDated, + SUBCTA = vSubaccount, + CONTRA = vAccount, + CONCEPTO = vConcept, + EURODEBE = vDebit, + EUROHABER = vCredit, + BASEEURO = vEuro, + SERIE = vSerie, + FACTURA = vInvoice, + IVA = vVat, + RECEQUIV = vRe, + AUXILIAR = IF(vAux = FALSE, NULL, '*'), + MONEDAUSO = 2, + empresa_id = vCompanyFk; + + SET vNewBookNumber = vBookNumber; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `zoneClosure_recalc` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -80323,29 +81534,6 @@ SET character_set_client = utf8; 1 AS `isRiskFree` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Agencias_province__` --- - -DROP TABLE IF EXISTS `Agencias_province__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Agencias_province__` ( - `province_id` smallint(6) unsigned NOT NULL, - `agency_id` smallint(5) unsigned NOT NULL, - `zona` tinyint(4) NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `route` tinyint(4) NOT NULL COMMENT 'Etiqueta zeleris', - `isVolumetric` tinyint(1) NOT NULL DEFAULT 0, - PRIMARY KEY (`province_id`,`agency_id`,`warehouse_id`), - KEY `warehouse_id` (`warehouse_id`), - KEY `agency_id` (`agency_id`), - CONSTRAINT `Agencias_province___ibfk_1` FOREIGN KEY (`province_id`) REFERENCES `vn`.`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Agencias_province___ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Agencias_province___ibfk_3` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Articles` -- @@ -80405,21 +81593,6 @@ SET character_set_client = utf8; 1 AS `packingOut` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Baldas__` --- - -DROP TABLE IF EXISTS `Baldas__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Baldas__` ( - `Id_Estanterias` int(11) NOT NULL, - `Id_Baldas` int(11) NOT NULL, - `h` int(11) NOT NULL, - PRIMARY KEY (`Id_Estanterias`,`Id_Baldas`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Bancos` -- @@ -80468,25 +81641,6 @@ SET character_set_client = utf8; 1 AS `insuranceExpired` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Brasa__` --- - -DROP TABLE IF EXISTS `Brasa__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Brasa__` ( - `Id_Cliente` int(10) unsigned NOT NULL DEFAULT 0, - `Cliente` varchar(50) NOT NULL, - `Vista` int(10) unsigned NOT NULL DEFAULT 0, - `Reg` bigint(21) unsigned NOT NULL DEFAULT 0, - `Consumo` double NOT NULL, - `Grupo` int(10) unsigned NOT NULL, - PRIMARY KEY (`Id_Cliente`), - KEY `Index_1` (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Cajas` -- @@ -80518,20 +81672,6 @@ SET character_set_client = utf8; 1 AS `Proveedores_account_Id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Clases__` --- - -DROP TABLE IF EXISTS `Clases__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clases__` ( - `Id_Clase` int(11) NOT NULL DEFAULT 0, - `Clase` varchar(50) DEFAULT NULL, - PRIMARY KEY (`Id_Clase`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Clientes` -- @@ -80586,92 +81726,6 @@ SET character_set_client = utf8; 1 AS `typeFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Clientes_dits__` --- - -DROP TABLE IF EXISTS `Clientes_dits__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clientes_dits__` ( - `idClientes_dits` int(11) NOT NULL AUTO_INCREMENT, - `idaccion_dits` int(11) NOT NULL, - `ODBC_DATE` timestamp NOT NULL DEFAULT current_timestamp(), - `Id_Ticket` int(11) NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `value_old` varchar(100) DEFAULT NULL, - `value_new` varchar(100) DEFAULT NULL, - PRIMARY KEY (`idClientes_dits`), - KEY `idaccion_dits` (`idaccion_dits`), - CONSTRAINT `Clientes_dits___ibfk_1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits__` (`idaccion_dits`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Clientes_empresa__` --- - -DROP TABLE IF EXISTS `Clientes_empresa__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clientes_empresa__` ( - `Id_Clientes_empresa` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL, - `empresa_id` int(10) unsigned NOT NULL, - `fecha_ini` date NOT NULL, - `fecha_fin` date NOT NULL, - PRIMARY KEY (`Id_Clientes_empresa`), - KEY `empresa_id_idx` (`empresa_id`), - CONSTRAINT `Clientes_empresaCompany_Fk` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Clientes_event__` --- - -DROP TABLE IF EXISTS `Clientes_event__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clientes_event__` ( - `Id_Cliente` int(11) NOT NULL, - `quantity` tinyint(3) unsigned NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT current_timestamp(), - PRIMARY KEY (`Id_Cliente`), - CONSTRAINT `Clientes_event___ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Clientes_potenciales__` --- - -DROP TABLE IF EXISTS `Clientes_potenciales__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clientes_potenciales__` ( - `id` int(11) NOT NULL, - `PAIS` varchar(12) DEFAULT NULL, - `ACTIVIDAD` varchar(10) DEFAULT NULL, - `NOMBRE` varchar(45) NOT NULL DEFAULT '', - `PROVINCIA` varchar(25) DEFAULT NULL, - `POBLACION` varchar(45) NOT NULL DEFAULT '', - `CP` varchar(10) DEFAULT NULL, - `DIR_POSTAL` varchar(45) NOT NULL DEFAULT '', - `TELEFONO` varchar(12) NOT NULL DEFAULT '', - `TELEFONO2` varchar(12) NOT NULL DEFAULT '', - `FAX` varchar(12) NOT NULL DEFAULT '', - `E-MAIL` varchar(45) DEFAULT NULL, - `pagweb` varchar(45) DEFAULT NULL, - `SERVICIOS` varchar(45) DEFAULT NULL, - `state_id` smallint(6) DEFAULT 0 COMMENT '0 no se ha hecho nada\n1 ya existe el cliente\n2 cliente conseguido\n3 desestimado', - `Id_Trabajador` smallint(6) DEFAULT NULL, - `Notas` varchar(255) DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT current_timestamp(), - PRIMARY KEY (`NOMBRE`,`POBLACION`,`DIR_POSTAL`,`TELEFONO`,`TELEFONO2`,`FAX`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Comparativa` -- @@ -80725,7 +81779,6 @@ SET character_set_client = utf8; 1 AS `Id_Trabajador`, 1 AS `weight`, 1 AS `dispatched`, - 1 AS `container_id`, 1 AS `itemOriginalFk` */; SET character_set_client = @saved_cs_client; @@ -80744,30 +81797,6 @@ SET character_set_client = utf8; 1 AS `odbc_date` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Compres_ok__` --- - -DROP TABLE IF EXISTS `Compres_ok__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Compres_ok__` ( - `Id_Compra` int(11) NOT NULL, - `valor` tinyint(3) unsigned NOT NULL DEFAULT 0, - `odbc_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), - `original_quantity` double DEFAULT NULL, - `Id_Trabajador` int(10) unsigned NOT NULL, - `Id_Accion` varchar(45) NOT NULL, - `Id_Compra_ok` int(11) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`Id_Compra_ok`), - KEY `Id_Movimiento` (`Id_Compra`), - KEY `Id_Accion` (`Id_Accion`), - KEY `Compres_ok_Id_Trabajador_idx` (`Id_Trabajador`), - CONSTRAINT `Compres_ok_Id_Trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`), - CONSTRAINT `Compres_ok___ibfk_1` FOREIGN KEY (`Id_Compra`) REFERENCES `vn`.`buy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Consignatarios` -- @@ -80794,39 +81823,6 @@ SET character_set_client = utf8; 1 AS `active` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Consignatarios_devices__` --- - -DROP TABLE IF EXISTS `Consignatarios_devices__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Consignatarios_devices__` ( - `Id_Consigna` int(11) NOT NULL, - `serialNumber` varchar(45) NOT NULL, - `notas` varchar(45) DEFAULT NULL, - PRIMARY KEY (`Id_Consigna`,`serialNumber`), - CONSTRAINT `Condigna_devices` FOREIGN KEY (`Id_Consigna`) REFERENCES `vn`.`address` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Conteo__` --- - -DROP TABLE IF EXISTS `Conteo__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Conteo__` ( - `Id_Conteo` int(11) NOT NULL AUTO_INCREMENT, - `Id_Article` int(11) NOT NULL, - `Fecha` timestamp NOT NULL DEFAULT current_timestamp(), - `dispositivo` varchar(15) DEFAULT NULL, - `warehouse_id` int(10) unsigned NOT NULL DEFAULT 1, - PRIMARY KEY (`Id_Conteo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Cubos` -- @@ -80918,24 +81914,6 @@ SET character_set_client = utf8; 1 AS `Id_Entrada` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Entradas_kop__` --- - -DROP TABLE IF EXISTS `Entradas_kop__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas_kop__` ( - `Id_Entradas_kop` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Entrada` int(11) NOT NULL, - `kop` int(11) DEFAULT NULL, - `sub` mediumint(8) unsigned DEFAULT NULL, - PRIMARY KEY (`Id_Entradas_kop`), - KEY `entradas_entradas_kop_idx` (`Id_Entrada`), - CONSTRAINT `entradas_entradas_kop` FOREIGN KEY (`Id_Entrada`) REFERENCES `vn`.`entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Entradas_orden` -- @@ -80949,85 +81927,6 @@ SET character_set_client = utf8; 1 AS `orden` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Espionajes__` --- - -DROP TABLE IF EXISTS `Espionajes__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Espionajes__` ( - `idEspionaje` int(11) NOT NULL AUTO_INCREMENT, - `Id_Trabajador` varchar(45) DEFAULT NULL, - `Fecha` date DEFAULT NULL, - `HoraEntrada` time DEFAULT NULL, - `HoraSalida` time DEFAULT NULL, - `Id_Equipo` int(11) DEFAULT NULL, - PRIMARY KEY (`idEspionaje`), - KEY `index` (`Id_Trabajador`,`Fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Estados__` --- - -DROP TABLE IF EXISTS `Estados__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Estados__` ( - `Id_Estado` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `Estado` varchar(50) DEFAULT NULL, - PRIMARY KEY (`Id_Estado`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Familias__` --- - -DROP TABLE IF EXISTS `Familias__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Familias__` ( - `Familia` varchar(3) NOT NULL, - `Subcuenta` varchar(10) DEFAULT NULL, - `Descripcion` varchar(50) DEFAULT NULL, - PRIMARY KEY (`Familia`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Forms__` --- - -DROP TABLE IF EXISTS `Forms__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Forms__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `titulo` varchar(50) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Grupos__` --- - -DROP TABLE IF EXISTS `Grupos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Grupos__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(50) NOT NULL, - `Grupo` varchar(45) NOT NULL, - `observation_type_id` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `name` (`name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Impresoras` -- @@ -81044,38 +81943,6 @@ SET character_set_client = utf8; 1 AS `isLabeler` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Informes__` --- - -DROP TABLE IF EXISTS `Informes__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Informes__` ( - `Id_Informe` tinyint(3) unsigned NOT NULL, - `Informe` varchar(50) DEFAULT NULL, - PRIMARY KEY (`Id_Informe`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Jefes__` --- - -DROP TABLE IF EXISTS `Jefes__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Jefes__` ( - `Id_Trabajador` int(10) unsigned NOT NULL, - `Id_Jefe` int(10) unsigned NOT NULL, - `Departamento` varchar(45) NOT NULL, - PRIMARY KEY (`Id_Trabajador`,`Id_Jefe`), - KEY `trabajador_jefe_idx` (`Id_Jefe`), - CONSTRAINT `trabajador_jefe` FOREIGN KEY (`Id_Jefe`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Monedas` -- @@ -81091,33 +81958,6 @@ SET character_set_client = utf8; 1 AS `Cambio` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Monitoring__` --- - -DROP TABLE IF EXISTS `Monitoring__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Monitoring__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `equipo_id` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - `user_id` int(10) unsigned NOT NULL, - `form_id` int(11) NOT NULL, - `cliente_id` int(11) NOT NULL, - `ticket_id` int(11) NOT NULL, - `ODBC_TIME` timestamp NOT NULL DEFAULT current_timestamp(), - PRIMARY KEY (`id`), - KEY `equipo_id` (`equipo_id`,`user_id`,`form_id`,`cliente_id`,`ticket_id`), - KEY `user_id` (`user_id`), - KEY `form_id` (`form_id`), - KEY `cliente_id` (`cliente_id`), - KEY `ticket_id` (`ticket_id`), - CONSTRAINT `Monitoring_FK` FOREIGN KEY (`equipo_id`) REFERENCES `vn`.`host` (`code`) ON UPDATE CASCADE, - CONSTRAINT `Monitoring___ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `vn`.`worker` (`id`), - CONSTRAINT `Monitoring___ibfk_3` FOREIGN KEY (`form_id`) REFERENCES `Forms__` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Movimientos` -- @@ -81143,23 +81983,6 @@ SET character_set_client = utf8; 1 AS `isAdded` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Movimientos_avisar__` --- - -DROP TABLE IF EXISTS `Movimientos_avisar__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Movimientos_avisar__` ( - `Id_Movimiento` int(11) NOT NULL, - `Id_Remitente` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Movimiento`), - KEY `Movimiento` (`Id_Movimiento`), - KEY `Remitente` (`Id_Remitente`), - CONSTRAINT `Id_Movimientos_avisar_fk` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Movimientos_componentes` -- @@ -81194,40 +82017,6 @@ SET character_set_client = utf8; 1 AS `stateFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Movimientos_revisar__` --- - -DROP TABLE IF EXISTS `Movimientos_revisar__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Movimientos_revisar__` ( - `Id_Movimiento` int(11) NOT NULL, - `Comentario` varchar(255) DEFAULT NULL, - `Revisado` tinyint(1) NOT NULL DEFAULT 0, - `Id_Remitente` int(11) DEFAULT NULL, - `Id_Destinatario` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Movimiento`), - KEY `Remitente` (`Id_Remitente`), - KEY `Destinatario` (`Id_Destinatario`), - CONSTRAINT `Movimientos_revisar___ibfk_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Objetivos__` --- - -DROP TABLE IF EXISTS `Objetivos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Objetivos__` ( - `Periodo` int(11) NOT NULL, - `Objetivo` double NOT NULL, - PRIMARY KEY (`Periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Ordenes` -- @@ -81308,26 +82097,6 @@ SET character_set_client = utf8; 1 AS `hasDailyInvoice` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Permisos__` --- - -DROP TABLE IF EXISTS `Permisos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Permisos__` ( - `Id_Grupo` int(10) unsigned NOT NULL, - `Id_Trabajador` int(10) unsigned NOT NULL, - `empresa_id` int(10) unsigned NOT NULL DEFAULT 442, - PRIMARY KEY (`Id_Grupo`,`Id_Trabajador`), - KEY `empresa_id` (`empresa_id`), - KEY `Permisos_ibfk_3_idx` (`Id_Trabajador`), - CONSTRAINT `PermisosCompany_Fk` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Permisos___ibfk_2` FOREIGN KEY (`Id_Grupo`) REFERENCES `Grupos__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Permisos___ibfk_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `PreciosEspeciales` -- @@ -81357,7 +82126,6 @@ SET character_set_client = utf8; 1 AS `cuenta`, 1 AS `pais_id`, 1 AS `NIF`, - 1 AS `Agricola`, 1 AS `Telefono`, 1 AS `cuentaret`, 1 AS `ComisionProveedor`, @@ -81397,41 +82165,6 @@ SET character_set_client = utf8; 1 AS `Id_Proveedor` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Proveedores_comunicados__` --- - -DROP TABLE IF EXISTS `Proveedores_comunicados__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Proveedores_comunicados__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Proveedor` int(10) unsigned NOT NULL, - `escrito_id` int(11) NOT NULL, - `fecha` timestamp NULL DEFAULT current_timestamp(), - PRIMARY KEY (`id`), - KEY `Proveedor` (`Id_Proveedor`), - KEY `Escrito` (`escrito_id`), - CONSTRAINT `Proveedores_comunicados___ibfk_4` FOREIGN KEY (`escrito_id`) REFERENCES `Proveedores_escritos__` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Proveedores_comunicados_supplierFk` FOREIGN KEY (`Id_Proveedor`) REFERENCES `vn`.`supplier` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Proveedores_escritos__` --- - -DROP TABLE IF EXISTS `Proveedores_escritos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Proveedores_escritos__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `escrito` varchar(45) NOT NULL, - `informe` varchar(45) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Proveedores_gestdoc` -- @@ -81466,21 +82199,6 @@ SET character_set_client = utf8; 1 AS `conciliado` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Recibos_recorded__` --- - -DROP TABLE IF EXISTS `Recibos_recorded__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Recibos_recorded__` ( - `Id_Recibos` int(11) NOT NULL, - `recorded` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Marcado si se ha contabilizado', - PRIMARY KEY (`Id_Recibos`), - CONSTRAINT `Recibos_recorded___ibfk_1` FOREIGN KEY (`Id_Recibos`) REFERENCES `vn`.`receipt` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Remesas` -- @@ -81496,34 +82214,6 @@ SET character_set_client = utf8; 1 AS `empresa_id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Reservas__` --- - -DROP TABLE IF EXISTS `Reservas__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Reservas__` ( - `Id_Reserva` int(11) NOT NULL AUTO_INCREMENT, - `Id_Ticket` int(11) DEFAULT 0, - `Fecha` datetime DEFAULT NULL, - `Alias` varchar(50) DEFAULT NULL, - `article` varchar(50) DEFAULT NULL, - `medida` varchar(50) DEFAULT NULL, - `categoria` varchar(50) DEFAULT NULL, - `color` varchar(50) DEFAULT NULL, - `origen` varchar(50) DEFAULT NULL, - `cantidad` int(11) DEFAULT 0, - `Id_Article` double DEFAULT 0, - `buyFk` int(11) NOT NULL, - `grouping` int(11) DEFAULT NULL, - `packing` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Reserva`), - KEY `Id_1` (`Id_Ticket`), - KEY `Id_Article` (`Id_Article`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Deprecated 27-02-2023'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Rutas` -- @@ -81567,21 +82257,6 @@ SET character_set_client = utf8; 1 AS `empresa_id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Series__` --- - -DROP TABLE IF EXISTS `Series__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Series__` ( - `Id_Serie` varchar(2) NOT NULL, - `Serie` varchar(30) DEFAULT NULL, - `Cuenta` varchar(10) DEFAULT NULL, - PRIMARY KEY (`Id_Serie`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Split_lines` -- @@ -81653,22 +82328,6 @@ SET character_set_client = utf8; 1 AS `totalWithoutVat` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Tickets_stack__` --- - -DROP TABLE IF EXISTS `Tickets_stack__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tickets_stack__` ( - `Id_Ticket` int(11) NOT NULL, - `orden` smallint(5) unsigned NOT NULL, - `label_number` smallint(6) DEFAULT 0, - `preparado` tinyint(4) DEFAULT 0, - PRIMARY KEY (`Id_Ticket`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Tickets_state` -- @@ -81743,20 +82402,6 @@ SET character_set_client = utf8; 1 AS `profit` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `Tipos_f11__` --- - -DROP TABLE IF EXISTS `Tipos_f11__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tipos_f11__` ( - `f11_id` tinyint(4) NOT NULL AUTO_INCREMENT, - `description` varchar(15) NOT NULL, - PRIMARY KEY (`f11_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `Trabajadores` -- @@ -81846,21 +82491,6 @@ SET character_set_client = utf8; 1 AS `gasoline` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `accion_dits__` --- - -DROP TABLE IF EXISTS `accion_dits__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accion_dits__` ( - `idaccion_dits` int(11) NOT NULL AUTO_INCREMENT, - `accion` varchar(255) DEFAULT NULL, - PRIMARY KEY (`idaccion_dits`), - UNIQUE KEY `accion_UNIQUE` (`accion`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `account_conciliacion` -- @@ -81909,24 +82539,6 @@ SET character_set_client = utf8; 1 AS `description` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `agencia_descuadre__` --- - -DROP TABLE IF EXISTS `agencia_descuadre__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `agencia_descuadre__` ( - `agencia_descuadre_id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Ticket` int(11) NOT NULL, - `date` date NOT NULL, - `price` double(7,2) NOT NULL, - `Consignatario` varchar(50) NOT NULL, - `Tipo` varchar(30) NOT NULL, - PRIMARY KEY (`agencia_descuadre_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `agency` -- @@ -81943,50 +82555,6 @@ SET character_set_client = utf8; 1 AS `workCenterFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `agency_hour__` --- - -DROP TABLE IF EXISTS `agency_hour__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `agency_hour__` ( - `agency_hour_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `week_day` tinyint(3) unsigned DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6', - `agency_id` smallint(5) unsigned DEFAULT NULL, - `warehouse_id` smallint(5) unsigned DEFAULT NULL, - `province_id` smallint(5) unsigned DEFAULT NULL, - `subtract_day` tinyint(10) unsigned NOT NULL COMMENT 'dias a restar de la Fecha de entrega', - `max_hour` tinyint(3) unsigned NOT NULL COMMENT 'maxima hora hasta la cual se pueden hacer pedidos', - PRIMARY KEY (`agency_hour_id`), - UNIQUE KEY `week_day` (`week_day`,`agency_id`,`warehouse_id`,`province_id`,`max_hour`), - KEY `agency_id` (`agency_id`), - KEY `warehouse_id` (`warehouse_id`), - KEY `province_id` (`province_id`), - CONSTRAINT `agency_hour___ibfk_1` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `agency_hour___ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `agency_hour___ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `vn`.`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `agency_warehouse__` --- - -DROP TABLE IF EXISTS `agency_warehouse__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `agency_warehouse__` ( - `agency_id` smallint(5) unsigned NOT NULL, - `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT 1, - `Vista` tinyint(3) unsigned NOT NULL DEFAULT 0, - PRIMARY KEY (`agency_id`,`warehouse_id`), - KEY `warehouse_id` (`warehouse_id`), - CONSTRAINT `agency_warehouse___ibfk_1` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agency` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `agency_warehouse___ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `airline` -- @@ -82035,8 +82603,7 @@ SET character_set_client = utf8; 1 AS `Id_Trabajador`, 1 AS `Id_Responsable`, 1 AS `department_id`, - 1 AS `recibida_id`, - 1 AS `farmingFk` */; + 1 AS `recibida_id` */; SET character_set_client = @saved_cs_client; -- @@ -82402,37 +82969,6 @@ SET character_set_client = utf8; 1 AS `description` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `call_information__` --- - -DROP TABLE IF EXISTS `call_information__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `call_information__` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Descripcio` text NOT NULL, - `Conclusio` tinyint(3) unsigned NOT NULL, - `Id_Cliente` int(11) NOT NULL, - `fecha` date NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `call_option__` --- - -DROP TABLE IF EXISTS `call_option__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `call_option__` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `descripcion` varchar(20) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `cdr` -- @@ -82522,20 +83058,6 @@ SET character_set_client = utf8; 1 AS `consecuencia` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `cl_dep__` --- - -DROP TABLE IF EXISTS `cl_dep__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_dep__` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `departamento` varchar(20) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `cl_det` -- @@ -82585,34 +83107,6 @@ SET character_set_client = utf8; 1 AS `motivo` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `cl_pet__` --- - -DROP TABLE IF EXISTS `cl_pet__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_pet__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `peticion` varchar(15) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_que__` --- - -DROP TABLE IF EXISTS `cl_que__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_que__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `queja` varchar(25) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `cl_res` -- @@ -82641,39 +83135,6 @@ SET character_set_client = utf8; 1 AS `addressFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `commission__` --- - -DROP TABLE IF EXISTS `commission__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `commission__` ( - `commisision_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `percentage` tinyint(3) unsigned NOT NULL, - `value` float unsigned NOT NULL, - PRIMARY KEY (`commisision_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `config__` --- - -DROP TABLE IF EXISTS `config__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `config__` ( - `id` int(11) NOT NULL, - `generic_item` int(11) NOT NULL COMMENT 'Id del artículo genérico', - `edi_entry` int(11) NOT NULL COMMENT 'Entrada usada para los EKTs', - `lastMana` int(11) NOT NULL DEFAULT 0, - `lastNicho` varchar(10) DEFAULT NULL, - `lastReserve` varchar(10) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `config_host` -- @@ -82692,26 +83153,6 @@ SET character_set_client = utf8; 1 AS `route_days_after` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `config_host_forms__` --- - -DROP TABLE IF EXISTS `config_host_forms__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `config_host_forms__` ( - `config_host_id` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - `formname` varchar(56) NOT NULL, - `x` int(8) NOT NULL, - `y` int(8) NOT NULL, - `h` int(8) NOT NULL, - `l` int(8) NOT NULL, - `odbc_date` timestamp NULL DEFAULT current_timestamp(), - PRIMARY KEY (`config_host_id`,`formname`), - CONSTRAINT `config_host_forms_FK` FOREIGN KEY (`config_host_id`) REFERENCES `vn`.`host` (`code`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `consignatarios_observation` -- @@ -82727,51 +83168,6 @@ SET character_set_client = utf8; 1 AS `text` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `container__` --- - -DROP TABLE IF EXISTS `container__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `container__` ( - `container_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `Continente` varchar(10) DEFAULT NULL, - PRIMARY KEY (`container_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cooler_path__` --- - -DROP TABLE IF EXISTS `cooler_path__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cooler_path__` ( - `cooler_path_id` int(11) NOT NULL AUTO_INCREMENT, - `description` varchar(45) DEFAULT NULL, - PRIMARY KEY (`cooler_path_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cp__` --- - -DROP TABLE IF EXISTS `cp__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cp__` ( - `cp_id` int(11) NOT NULL AUTO_INCREMENT, - `cpd` int(11) NOT NULL, - `cph` int(11) NOT NULL, - `zone_id` smallint(6) DEFAULT NULL, - `town` varchar(45) NOT NULL, - PRIMARY KEY (`cp_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `credit` -- @@ -82788,62 +83184,6 @@ SET character_set_client = utf8; 1 AS `odbc_date` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `credit_card__` --- - -DROP TABLE IF EXISTS `credit_card__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `credit_card__` ( - `credit_card_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(10) NOT NULL, - `number` varchar(20) NOT NULL, - `expiration_month` tinyint(2) unsigned zerofill NOT NULL, - `expiration_year` tinyint(2) unsigned zerofill NOT NULL, - `priority` tinyint(3) unsigned NOT NULL DEFAULT 1, - `obs` varchar(45) DEFAULT NULL, - PRIMARY KEY (`credit_card_id`), - KEY `Id_Cliente` (`Id_Cliente`), - CONSTRAINT `credit_card___ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cyc__` --- - -DROP TABLE IF EXISTS `cyc__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cyc__` ( - `Id_Cliente` int(11) NOT NULL, - `Riesgo` double DEFAULT NULL, - `Fecha` timestamp NOT NULL DEFAULT current_timestamp(), - `cyc_id` int(11) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`cyc_id`), - KEY `Cliente` (`Id_Cliente`), - CONSTRAINT `Cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cyc_declaration__` --- - -DROP TABLE IF EXISTS `cyc_declaration__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cyc_declaration__` ( - `factura_id` int(10) unsigned NOT NULL, - `Riesgo` double DEFAULT NULL, - `Fecha` date NOT NULL, - `Vencimiento` int(10) NOT NULL DEFAULT 0, - PRIMARY KEY (`factura_id`), - CONSTRAINT `Factura` FOREIGN KEY (`factura_id`) REFERENCES `vn`.`invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `definitivo` -- @@ -82860,37 +83200,6 @@ SET character_set_client = utf8; 1 AS `fecha` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `dock__` --- - -DROP TABLE IF EXISTS `dock__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `dock__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `code` varchar(5) NOT NULL, - `xPos` int(11) DEFAULT NULL, - `yPos` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `code_UNIQUE` (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-03-05'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `duaDismissed__` --- - -DROP TABLE IF EXISTS `duaDismissed__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `duaDismissed__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ticketFk` varchar(45) NOT NULL, - PRIMARY KEY (`id`,`ticketFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `edi_article` -- @@ -82976,36 +83285,6 @@ SET character_set_client = utf8; 1 AS `company_name` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `edi_testigos__` --- - -DROP TABLE IF EXISTS `edi_testigos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `edi_testigos__` ( - `id` smallint(6) NOT NULL AUTO_INCREMENT, - `table` varchar(25) NOT NULL, - `field` varchar(32) NOT NULL, - `testigo` varchar(5) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `emp_day_pay__` --- - -DROP TABLE IF EXISTS `emp_day_pay__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `emp_day_pay__` ( - `id` smallint(5) unsigned NOT NULL, - `emp_day_pay` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`id`,`emp_day_pay`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `empresa` -- @@ -83090,65 +83369,6 @@ SET character_set_client = utf8; 1 AS `observationWorkerCode` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `expeditions_deleted__` --- - -DROP TABLE IF EXISTS `expeditions_deleted__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `expeditions_deleted__` ( - `expeditions_id` int(11) NOT NULL AUTO_INCREMENT, - `agency_id` int(11) NOT NULL, - `ticket_id` int(10) NOT NULL, - `EsBulto` int(11) DEFAULT 1, - `odbc_date` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), - `reembolso` bit(1) DEFAULT b'0', - `recogida` bit(1) DEFAULT b'0', - `Id_Article` int(11) DEFAULT NULL, - `counter` smallint(5) unsigned NOT NULL, - `checked` tinyint(4) NOT NULL DEFAULT 0, - `completed` tinyint(4) DEFAULT 0, - `expedicion` varchar(45) DEFAULT NULL, - `Id_Trabajador` int(11) DEFAULT NULL, - PRIMARY KEY (`expeditions_id`), - KEY `index1` (`agency_id`), - KEY `index2` (`EsBulto`), - KEY `index3` (`odbc_date`), - KEY `index4` (`ticket_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `expeditions_pictures__` --- - -DROP TABLE IF EXISTS `expeditions_pictures__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `expeditions_pictures__` ( - `Id_Article` int(11) NOT NULL, - `NoImprimirEtiqueta` bit(1) DEFAULT b'0', - PRIMARY KEY (`Id_Article`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6371 deprecated 2024-01-11'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `filtros__` --- - -DROP TABLE IF EXISTS `filtros__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `filtros__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(45) NOT NULL, - `sql` varchar(255) NOT NULL, - `Estanteria` tinyint(1) DEFAULT 0, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-21;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `financialProductType` -- @@ -83181,23 +83401,6 @@ SET character_set_client = utf8; 1 AS `airport_in` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `form_query__` --- - -DROP TABLE IF EXISTS `form_query__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `form_query__` ( - `form_query_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `query` varchar(50) NOT NULL, - `response1` varchar(10) NOT NULL, - `response2` varchar(10) NOT NULL, - `type_id` enum('gest_doc') NOT NULL, - PRIMARY KEY (`form_query_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-21;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `gastos_resumen` -- @@ -83215,38 +83418,6 @@ SET character_set_client = utf8; 1 AS `empresa_id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `guillen__` --- - -DROP TABLE IF EXISTS `guillen__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `guillen__` ( - `bulto` tinyint(3) unsigned NOT NULL, - `1` float unsigned NOT NULL, - `2` float unsigned NOT NULL, - `re_exp` float unsigned NOT NULL, - PRIMARY KEY (`bulto`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `guillen_carry__` --- - -DROP TABLE IF EXISTS `guillen_carry__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `guillen_carry__` ( - `carry` tinyint(3) unsigned NOT NULL, - `1` float unsigned NOT NULL, - `2` float unsigned NOT NULL, - `re_exp` float unsigned NOT NULL, - PRIMARY KEY (`carry`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `integra2` -- @@ -83261,23 +83432,6 @@ SET character_set_client = utf8; 1 AS `warehouse_id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `integra2_escala__` --- - -DROP TABLE IF EXISTS `integra2_escala__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `integra2_escala__` ( - `province_id` smallint(6) unsigned NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`province_id`,`warehouse_id`), - KEY `warehouse_escala_idx` (`warehouse_id`), - CONSTRAINT `province_escala` FOREIGN KEY (`province_id`) REFERENCES `vn`.`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_escala` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `integra2_province` -- @@ -83291,72 +83445,6 @@ SET character_set_client = utf8; 1 AS `franquicia` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `invoice_observation__` --- - -DROP TABLE IF EXISTS `invoice_observation__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoice_observation__` ( - `invoice_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `desde` date NOT NULL, - `hasta` date NOT NULL, - `serie` varchar(1) NOT NULL DEFAULT '0', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT 0, - `text` text NOT NULL, - PRIMARY KEY (`invoice_observation_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `jerarquia__` --- - -DROP TABLE IF EXISTS `jerarquia__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `jerarquia__` ( - `worker_id` int(10) unsigned NOT NULL, - `boss_id` int(10) unsigned NOT NULL, - `vinculado` tinyint(3) unsigned NOT NULL DEFAULT 0, - PRIMARY KEY (`worker_id`,`boss_id`), - KEY `worker_trabajador` (`worker_id`), - KEY `jerarquiaBossFk_idx` (`boss_id`), - CONSTRAINT `jerarquiaBossFk` FOREIGN KEY (`boss_id`) REFERENCES `account`.`account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `jerarquiaWorkerFk` FOREIGN KEY (`worker_id`) REFERENCES `account`.`account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #7258 @deprecated 2023-12-13'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `language__` --- - -DROP TABLE IF EXISTS `language__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `language__` ( - `code` varchar(10) NOT NULL, - `name` varchar(20) NOT NULL, - `active` tinyint(1) NOT NULL DEFAULT 0, - PRIMARY KEY (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `link__` --- - -DROP TABLE IF EXISTS `link__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `link__` ( - `Id_Cliente` int(11) NOT NULL, - `Id_Proveedor` int(11) NOT NULL, - PRIMARY KEY (`Id_Cliente`,`Id_Proveedor`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `mail` -- @@ -83411,19 +83499,6 @@ SET character_set_client = utf8; 1 AS `Nombre` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `nichos__` --- - -DROP TABLE IF EXISTS `nichos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nichos__` ( - `id` varchar(5) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `pago` -- @@ -83515,45 +83590,6 @@ SET character_set_client = utf8; 1 AS `isNotified` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `payroll_basess__` --- - -DROP TABLE IF EXISTS `payroll_basess__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_basess__` ( - `id_payroll_Basess` int(11) NOT NULL AUTO_INCREMENT, - `empresa_id` int(10) NOT NULL, - `id_tipobasess` int(11) NOT NULL, - `valor` double NOT NULL, - `fechadesde` date NOT NULL, - `fechahasta` date DEFAULT NULL, - `contratotemporal` tinyint(1) DEFAULT 0, - PRIMARY KEY (`id_payroll_Basess`), - KEY `payroll_basess_1_idx` (`id_tipobasess`), - KEY `payroll_basess_2_idx` (`empresa_id`), - CONSTRAINT `payroll_basess_1` FOREIGN KEY (`id_tipobasess`) REFERENCES `payroll_tipobasess__` (`id_payroll_tipobasess`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `payroll_basess_2` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`payrollWorkCenter` (`empresa_id__`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_bonificaciones__` --- - -DROP TABLE IF EXISTS `payroll_bonificaciones__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_bonificaciones__` ( - `codtrabajador` int(11) NOT NULL, - `codempresa` int(11) NOT NULL, - `Fecha` date NOT NULL, - `bonificacionSS` double NOT NULL, - PRIMARY KEY (`codtrabajador`,`codempresa`,`Fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `payroll_categorias` -- @@ -83597,49 +83633,6 @@ SET character_set_client = utf8; 1 AS `isException` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `payroll_datos__` --- - -DROP TABLE IF EXISTS `payroll_datos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_datos__` ( - `codtrabajador` int(11) NOT NULL, - `codempresa` int(10) NOT NULL, - `Fecha` date NOT NULL, - `conceptoid` int(11) NOT NULL, - `orden` tinyint(4) DEFAULT NULL, - `dias` smallint(6) DEFAULT NULL, - `Importe` decimal(8,2) NOT NULL, - `DH` tinyint(4) DEFAULT NULL, - `T_Paga` tinyint(4) NOT NULL, - `TributaIRPF` tinyint(4) NOT NULL, - PRIMARY KEY (`codtrabajador`,`codempresa`,`conceptoid`,`Fecha`), - KEY `fgkey_payrolldatos_1_idx` (`conceptoid`), - CONSTRAINT `fgkey_payrolldatos_1` FOREIGN KEY (`conceptoid`) REFERENCES `vn`.`payrollComponent` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_embargos__` --- - -DROP TABLE IF EXISTS `payroll_embargos__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_embargos__` ( - `codtrabajador` int(11) NOT NULL, - `codempresa` int(10) NOT NULL, - `conceptoid` int(11) NOT NULL, - `Fecha` date NOT NULL, - `pagado` double NOT NULL, - `pendiente` double DEFAULT NULL, - `total` double NOT NULL, - PRIMARY KEY (`codtrabajador`,`codempresa`,`Fecha`,`conceptoid`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `payroll_employee` -- @@ -83654,41 +83647,6 @@ SET character_set_client = utf8; 1 AS `workerFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `payroll_tipobasess__` --- - -DROP TABLE IF EXISTS `payroll_tipobasess__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_tipobasess__` ( - `id_payroll_tipobasess` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id_payroll_tipobasess`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payrroll_apEmpresarial__` --- - -DROP TABLE IF EXISTS `payrroll_apEmpresarial__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payrroll_apEmpresarial__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `codTrabajador` int(11) NOT NULL, - `Fecha` date NOT NULL, - `CosteEmpresaAT` decimal(8,2) NOT NULL, - `costeEmpresaCC` decimal(8,2) NOT NULL, - `costeEmpresaDesempleo` decimal(8,2) NOT NULL, - `costeEmpresaFP` decimal(8,2) NOT NULL, - `costeEmpresaFogasa` decimal(8,2) NOT NULL, - `costeEmpresaExtra` decimal(8,2) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `plantpassport` -- @@ -83718,22 +83676,6 @@ SET character_set_client = utf8; 1 AS `Paises_Id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `preparation_exception__` --- - -DROP TABLE IF EXISTS `preparation_exception__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `preparation_exception__` ( - `exception_day` date NOT NULL COMMENT 'preparation day', - `warehouse_id` smallint(6) unsigned DEFAULT NULL, - `percentage` tinyint(2) NOT NULL DEFAULT 0, - UNIQUE KEY `exception_day_UNIQUE` (`exception_day`), - UNIQUE KEY `warehouse_id_UNIQUE` (`warehouse_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `price_fixed` -- @@ -83805,22 +83747,6 @@ SET character_set_client = utf8; 1 AS `geoFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `rec_translator__` --- - -DROP TABLE IF EXISTS `rec_translator__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `rec_translator__` ( - `Id_Article` int(11) NOT NULL, - `denominacion` varchar(85) NOT NULL, - PRIMARY KEY (`Id_Article`,`denominacion`), - KEY `id_article_rec_idx` (`Id_Article`), - CONSTRAINT `id_article_rec` FOREIGN KEY (`Id_Article`) REFERENCES `vn`.`item` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `recibida` -- @@ -83854,21 +83780,6 @@ SET character_set_client = utf8; 1 AS `expenseFkDeductible` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `recibida_agricola__` --- - -DROP TABLE IF EXISTS `recibida_agricola__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recibida_agricola__` ( - `recibida_id` mediumint(8) unsigned NOT NULL, - `num` smallint(5) unsigned NOT NULL, - PRIMARY KEY (`recibida_id`), - CONSTRAINT `recibida_agricola___ibfk_1` FOREIGN KEY (`recibida_id`) REFERENCES `vn`.`invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `recibida_intrastat` -- @@ -83971,150 +83882,6 @@ SET character_set_client = utf8; 1 AS `efimero` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `rounding__` --- - -DROP TABLE IF EXISTS `rounding__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `rounding__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `amount` double NOT NULL DEFAULT 0, - `price` double DEFAULT 0, - `discount` double NOT NULL DEFAULT 0, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `route__` --- - -DROP TABLE IF EXISTS `route__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `route__` ( - `agency_id` smallint(5) unsigned NOT NULL, - `week_day` tinyint(3) unsigned NOT NULL COMMENT 'weekday de access el domingo = 1, sabado = 7. Intentar cambiar al de Mysql Lunes = 0', - PRIMARY KEY (`agency_id`,`week_day`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `scanTree__` --- - -DROP TABLE IF EXISTS `scanTree__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `scanTree__` ( - `id` int(11) NOT NULL DEFAULT 0, - `name` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - `lft` int(11) NOT NULL, - `rgt` int(11) NOT NULL, - `depth` bigint(22) NOT NULL DEFAULT 0, - `sons` int(11) DEFAULT 0, - `lastScanned` datetime DEFAULT NULL, - `routeCount` int(11) DEFAULT NULL, - `minRoute` int(11) DEFAULT NULL, - `maxRoute` int(11) DEFAULT NULL, - `scanned` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `lft_rgt_depth` (`lft`,`rgt`,`depth`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `scan__` --- - -DROP TABLE IF EXISTS `scan__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `scan__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `lft` int(11) NOT NULL, - `rgt` int(11) NOT NULL, - `name` varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT current_timestamp(), - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `scan_line__` --- - -DROP TABLE IF EXISTS `scan_line__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `scan_line__` ( - `scan_line_id` int(11) NOT NULL AUTO_INCREMENT, - `scan_id` int(11) NOT NULL, - `code` varchar(45) NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT current_timestamp(), - PRIMARY KEY (`scan_line_id`), - KEY `id_scan_id_idx` (`scan_id`), - CONSTRAINT `id_scan_id` FOREIGN KEY (`scan_id`) REFERENCES `scan__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sort_merge_results_ernesto__` --- - -DROP TABLE IF EXISTS `sort_merge_results_ernesto__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sort_merge_results_ernesto__` ( - `hora` datetime NOT NULL, - `uptime` int(11) DEFAULT NULL, - `log_output` varchar(5) DEFAULT NULL, - `uptime_since_flush` int(11) DEFAULT NULL, - `smp_old` int(11) DEFAULT NULL, - `smp_new` int(11) DEFAULT NULL, - `smp` int(11) DEFAULT NULL, - `smp_hour` int(11) DEFAULT NULL, - `connections` int(11) DEFAULT NULL, - `Threads_created` int(11) DEFAULT NULL, - `Threads_cached` int(11) DEFAULT NULL, - `Thread_cache_size` int(11) DEFAULT NULL, - `comment` varchar(255) DEFAULT NULL, - `TABLE_OPEN_CACHE_OVERFLOWS` int(11) DEFAULT NULL, - `TABLE_OPEN_CACHE_MISSES` int(11) DEFAULT NULL, - `TABLE_OPEN_CACHE_HITS` int(11) DEFAULT NULL, - `table_open_cache` int(11) DEFAULT NULL, - `table_open_cache_instances` int(11) DEFAULT NULL, - `open_tables` int(11) DEFAULT NULL, - `opened_tables` int(11) DEFAULT NULL, - `Innodb_os_log_written` double DEFAULT NULL, - `table_definition_cache` int(11) DEFAULT NULL, - `Open_table_definitions` int(11) DEFAULT NULL, - `sort_buffer_size` int(11) DEFAULT NULL, - `join_buffer_size` int(11) DEFAULT NULL, - `read_rnd_buffer_size` int(11) DEFAULT NULL, - `tmp_table_size` int(11) DEFAULT NULL, - `max_heap_table_size` int(11) DEFAULT NULL, - `created_tmp_disk_tables` int(11) DEFAULT NULL, - `created_tmp_tables` int(11) DEFAULT NULL, - `Created_tmp_files` int(11) DEFAULT NULL, - `OpenTablesxUptimeDivOpened` float DEFAULT NULL, - `innodb_open_files` int(11) DEFAULT NULL, - `Innodb_num_open_files` int(11) DEFAULT NULL, - `open_files_limit` int(11) DEFAULT NULL, - `query_cache_size` int(11) DEFAULT NULL, - `query_cache_type` varchar(3) DEFAULT NULL, - `trx_rseg_history_len` int(11) DEFAULT NULL, - `Qcache_hits` int(11) DEFAULT NULL, - `Qcache_inserts` int(11) DEFAULT NULL, - `Qcache_not_cached` int(11) DEFAULT NULL, - PRIMARY KEY (`hora`), - UNIQUE KEY `hora_UNIQUE` (`hora`), - KEY `uptime` (`uptime`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `state` -- @@ -84229,78 +83996,6 @@ SET character_set_client = utf8; 1 AS `ASIEN` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `tblIVA__` --- - -DROP TABLE IF EXISTS `tblIVA__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tblIVA__` ( - `tipoiva` varchar(50) NOT NULL, - `iva` smallint(6) NOT NULL DEFAULT 0, - `cuenta` double DEFAULT 0, - `cuentaRE` double DEFAULT 0, - `cuentaivaRE` double DEFAULT 0, - `REQ` double DEFAULT 0, - PRIMARY KEY (`tipoiva`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `template_bionic_component__` --- - -DROP TABLE IF EXISTS `template_bionic_component__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `template_bionic_component__` ( - `warehouse_id` smallint(5) unsigned NOT NULL, - `item_id` int(11) NOT NULL, - `component_id` int(10) unsigned NOT NULL, - `cost` decimal(10,4) NOT NULL, - UNIQUE KEY `item_warehouse_component` (`item_id`,`warehouse_id`,`component_id`) USING HASH, - KEY `item_warehouse` (`item_id`,`warehouse_id`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `template_bionic_lot__` --- - -DROP TABLE IF EXISTS `template_bionic_lot__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `template_bionic_lot__` ( - `warehouse_id` smallint(5) unsigned NOT NULL, - `item_id` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buy_id` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT 0, - UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`), - KEY `item_id` (`item_id`) -) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `template_bionic_price__` --- - -DROP TABLE IF EXISTS `template_bionic_price__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `template_bionic_price__` ( - `warehouse_id` smallint(5) unsigned NOT NULL, - `item_id` int(11) NOT NULL, - `rate` tinyint(3) unsigned NOT NULL, - `items` int(11) DEFAULT NULL, - `grouping` int(11) DEFAULT NULL, - `price` decimal(10,2) DEFAULT NULL, - UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`,`rate`), - KEY `item_id` (`item_id`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `thermograph` -- @@ -84360,52 +84055,6 @@ SET character_set_client = utf8; 1 AS `yearMonth` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `tipsa__` --- - -DROP TABLE IF EXISTS `tipsa__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tipsa__` ( - `kilos` tinyint(3) unsigned NOT NULL, - `importe` double unsigned NOT NULL, - `zona` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`kilos`,`zona`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tmpNEWTARIFAS__` --- - -DROP TABLE IF EXISTS `tmpNEWTARIFAS__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tmpNEWTARIFAS__` ( - `Id_Cliente` int(11) NOT NULL, - `Cliente` varchar(50) NOT NULL, - `Consumo_medio_mensual` double(17,0) DEFAULT NULL, - `Tarifa_Actual` int(11) DEFAULT 0, - `Nueva_Tarifa` int(11) DEFAULT NULL, - `Id_Trabajador` int(11) DEFAULT 20, - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `transport__` --- - -DROP TABLE IF EXISTS `transport__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `transport__` ( - `wday` tinyint(4) NOT NULL, - PRIMARY KEY (`wday`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `travel` -- @@ -84434,196 +84083,6 @@ SET character_set_client = utf8; 1 AS `awbFk` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `travel_pattern__` --- - -DROP TABLE IF EXISTS `travel_pattern__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `travel_pattern__` ( - `travel_pattern_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `week_start` tinyint(3) unsigned NOT NULL, - `week_end` tinyint(3) unsigned NOT NULL, - `warehouse_out` smallint(5) unsigned NOT NULL, - `warehouse_in` smallint(5) unsigned NOT NULL, - `agency_id` int(11) NOT NULL, - `day_out` tinyint(3) unsigned NOT NULL, - `duration` tinyint(3) unsigned NOT NULL, - `ref` varchar(20) NOT NULL, - `cargoSupplierFk` int(10) unsigned DEFAULT NULL, - `kg` decimal(10,0) unsigned DEFAULT NULL, - `travelFk` int(10) unsigned DEFAULT NULL COMMENT 'travel origen para clonar ademas sus entradas', - PRIMARY KEY (`travel_pattern_id`), - KEY `warehouse_out` (`warehouse_out`), - KEY `warehouse_in` (`warehouse_in`), - KEY `agency_id` (`agency_id`), - KEY `travel_pattern_ibfk_6_idx` (`cargoSupplierFk`), - KEY `travel_pattern_FK` (`travelFk`), - CONSTRAINT `travel_pattern_FK` FOREIGN KEY (`travelFk`) REFERENCES `vn`.`travel` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_pattern___ibfk_3` FOREIGN KEY (`warehouse_out`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_pattern___ibfk_4` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_pattern___ibfk_5` FOREIGN KEY (`warehouse_in`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_pattern_supplierFk` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `vn`.`supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `travel_reserve__` --- - -DROP TABLE IF EXISTS `travel_reserve__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `travel_reserve__` ( - `travel_reserve_id` int(11) NOT NULL AUTO_INCREMENT, - `travel_id` int(11) unsigned NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `reserved` decimal(4,1) DEFAULT NULL, - `buyed` decimal(4,1) DEFAULT NULL, - `askingfor` decimal(4,1) DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT current_timestamp(), - `labeled` decimal(4,1) unsigned NOT NULL DEFAULT 0.0, - PRIMARY KEY (`Id_Trabajador`,`travel_id`), - UNIQUE KEY `travel_reserve_id_UNIQUE` (`travel_reserve_id`), - KEY `travel_travel_reserve_idx` (`travel_id`), - KEY `traveL_buyer_id_idx` (`Id_Trabajador`), - CONSTRAINT `travel_reserve___ibfk_1` FOREIGN KEY (`travel_id`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `trolley__` --- - -DROP TABLE IF EXISTS `trolley__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `trolley__` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `fecha` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), - `ref` varchar(4) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unaryScanFilter__` --- - -DROP TABLE IF EXISTS `unaryScanFilter__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unaryScanFilter__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(50) NOT NULL, - `filter` text NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unary__` --- - -DROP TABLE IF EXISTS `unary__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unary__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `parent` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `idunary_UNIQUE` (`id`), - KEY `unary_parent_idx` (`parent`), - CONSTRAINT `unary_parent` FOREIGN KEY (`parent`) REFERENCES `unary__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #7258 @deprecated 2023-12-13'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unary_scan__` --- - -DROP TABLE IF EXISTS `unary_scan__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unary_scan__` ( - `unary_id` int(11) NOT NULL, - `name` varchar(45) DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT current_timestamp(), - `type` set('BUYS','EXPEDITIONS') NOT NULL, - PRIMARY KEY (`unary_id`), - KEY `scan_unary_idx` (`unary_id`), - CONSTRAINT `unary_scan` FOREIGN KEY (`unary_id`) REFERENCES `unary__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unary_scan_line__` --- - -DROP TABLE IF EXISTS `unary_scan_line__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unary_scan_line__` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `code` varchar(45) NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT current_timestamp(), - `unary_id` int(11) NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `id_UNIQUE` (`id`), - KEY `unary_line_idx` (`unary_id`), - CONSTRAINT `unary_line` FOREIGN KEY (`unary_id`) REFERENCES `unary_scan__` (`unary_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unary_scan_line_buy__` --- - -DROP TABLE IF EXISTS `unary_scan_line_buy__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unary_scan_line_buy__` ( - `scan_line_id` int(11) NOT NULL, - `Id_Article` int(11) NOT NULL, - PRIMARY KEY (`scan_line_id`), - UNIQUE KEY `scan_line_id_UNIQUE` (`scan_line_id`), - KEY `Id_Article_buy_idx` (`Id_Article`), - CONSTRAINT `Id_Article_buy` FOREIGN KEY (`Id_Article`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `scan_line_id_patriarcal` FOREIGN KEY (`scan_line_id`) REFERENCES `unary_scan_line__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unary_scan_line_expedition__` --- - -DROP TABLE IF EXISTS `unary_scan_line_expedition__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unary_scan_line_expedition__` ( - `scan_line_id` int(11) NOT NULL, - `expedition_id` int(11) NOT NULL, - PRIMARY KEY (`scan_line_id`), - UNIQUE KEY `scan_line_id_UNIQUE` (`scan_line_id`), - KEY `expedition_id_scan_idx` (`expedition_id`), - CONSTRAINT `expedition_id_scan` FOREIGN KEY (`expedition_id`) REFERENCES `vn`.`expedition` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `unary_source__` --- - -DROP TABLE IF EXISTS `unary_source__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `unary_source__` ( - `name` varchar(100) NOT NULL, - PRIMARY KEY (`name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `v_Articles_botanical` -- @@ -84743,90 +84202,6 @@ SET character_set_client = utf8; 1 AS `critical` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `viaxpress__` --- - -DROP TABLE IF EXISTS `viaxpress__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `viaxpress__` ( - `codigo_postal` varchar(5) NOT NULL, - `zona` tinyint(4) NOT NULL DEFAULT 2, - `m_t` tinyint(4) NOT NULL DEFAULT 0, - `POBLACION` varchar(25) NOT NULL, - `PROVINCIA` varchar(20) NOT NULL, - PRIMARY KEY (`codigo_postal`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouse_filtro__` --- - -DROP TABLE IF EXISTS `warehouse_filtro__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_filtro__` ( - `warehouse_id` smallint(6) unsigned NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `ok` tinyint(3) unsigned DEFAULT 1, - PRIMARY KEY (`Id_Trabajador`,`warehouse_id`), - KEY `wh_worker_idx` (`Id_Trabajador`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouse_group__` --- - -DROP TABLE IF EXISTS `warehouse_group__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_group__` ( - `warehouse_alias_id` smallint(5) unsigned NOT NULL DEFAULT 22, - `warehouse_id` smallint(5) unsigned NOT NULL, - PRIMARY KEY (`warehouse_alias_id`,`warehouse_id`), - KEY `warehosue_group_ware_idx` (`warehouse_id`), - CONSTRAINT `warehosue_group_ware` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_group_alias` FOREIGN KEY (`warehouse_alias_id`) REFERENCES `vn`.`warehouseAlias__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouse_joined__` --- - -DROP TABLE IF EXISTS `warehouse_joined__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_joined__` ( - `warehouse_id` smallint(5) unsigned NOT NULL, - `warehouse_alias_id` smallint(5) unsigned NOT NULL, - PRIMARY KEY (`warehouse_id`,`warehouse_alias_id`), - CONSTRAINT `warehouse_joined___ibfk_3` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouse_lc__` --- - -DROP TABLE IF EXISTS `warehouse_lc__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_lc__` ( - `whin` smallint(6) unsigned NOT NULL, - `whout` smallint(6) unsigned NOT NULL, - `m3` double NOT NULL DEFAULT 15, - `days` int(11) NOT NULL DEFAULT 1, - PRIMARY KEY (`whin`,`whout`), - KEY `whout_wh_idx` (`whout`), - CONSTRAINT `whin_wh` FOREIGN KEY (`whin`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `whout_wh` FOREIGN KEY (`whout`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Temporary table structure for view `warehouse_pickup` -- @@ -84840,71 +84215,6 @@ SET character_set_client = utf8; 1 AS `agency_id` */; SET character_set_client = @saved_cs_client; --- --- Table structure for table `wh_selection__` --- - -DROP TABLE IF EXISTS `wh_selection__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `wh_selection__` ( - `Id_Trabajador` int(10) unsigned NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`Id_Trabajador`,`warehouse_id`), - KEY `Trabajadores` (`Id_Trabajador`), - KEY `Warehouse` (`warehouse_id`), - CONSTRAINT `Trabajadores` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-11-28;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `widget__` --- - -DROP TABLE IF EXISTS `widget__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `widget__` ( - `widget_id` int(11) NOT NULL, - `chr` int(11) NOT NULL, - PRIMARY KEY (`widget_id`), - UNIQUE KEY `chr_UNIQUE` (`chr`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `wks__` --- - -DROP TABLE IF EXISTS `wks__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `wks__` ( - `wk` int(10) unsigned NOT NULL, - `yr` int(10) unsigned NOT NULL, - `vwk` int(10) unsigned NOT NULL, - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `comments` text DEFAULT NULL, - PRIMARY KEY (`id`) USING BTREE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `zones__` --- - -DROP TABLE IF EXISTS `zones__`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zones__` ( - `zone_id` tinyint(4) NOT NULL, - `name` varchar(45) NOT NULL, - `printingOrder` int(11) NOT NULL DEFAULT 0, - PRIMARY KEY (`zone_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='refs #6372 @deprecated 2023-12-13;'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Dumping events for database 'vn2008' -- @@ -85779,7 +85089,7 @@ USE `pbx`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,`s`.`extension` AS `regexten`,NULL AS `callbackextension`,`s`.`md5Secret` AS `md5secret`,`u`.`nickname` AS `callerid`,`c`.`host` AS `host`,`c`.`deny` AS `deny`,`c`.`permit` AS `permit`,`c`.`type` AS `type`,`c`.`context` AS `context`,`c`.`incomingLimit` AS `incominglimit`,`c`.`pickupGroup` AS `pickupgroup`,`c`.`directMedia` AS `directmedia`,`c`.`insecure` AS `insecure`,`c`.`transport` AS `transport`,`c`.`nat` AS `nat`,`c`.`disallow` AS `disallow`,`c`.`allow` AS `allow`,`r`.`ipAddr` AS `ipaddr`,`r`.`regSeconds` AS `regseconds`,`r`.`port` AS `port`,`r`.`defaultUser` AS `defaultuser`,`r`.`userAgent` AS `useragent`,`r`.`lastMs` AS `lastms`,`r`.`fullContact` AS `fullcontact`,`r`.`regServer` AS `regserver` from (((`pbx`.`sip` `s` join `account`.`user` `u` on(`u`.`id` = `s`.`user_id`)) left join `pbx`.`sipReg` `r` on(`s`.`user_id` = `r`.`userId`)) join `pbx`.`sipConfig` `c`) */; +/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,`s`.`extension` AS `regexten`,NULL AS `callbackextension`,`s`.`md5Secret` AS `md5secret`,`u`.`nickname` AS `callerid`,`c`.`host` AS `host`,`c`.`deny` AS `deny`,`c`.`permit` AS `permit`,`c`.`type` AS `type`,`c`.`context` AS `context`,`c`.`call-limit` AS `call-limit`,`c`.`pickupGroup` AS `pickupgroup`,`c`.`directMedia` AS `directmedia`,`c`.`insecure` AS `insecure`,`c`.`transport` AS `transport`,`c`.`nat` AS `nat`,`c`.`disallow` AS `disallow`,`c`.`allow` AS `allow`,`r`.`ipAddr` AS `ipaddr`,`r`.`regSeconds` AS `regseconds`,`r`.`port` AS `port`,`r`.`defaultUser` AS `defaultuser`,`r`.`userAgent` AS `useragent`,`r`.`lastMs` AS `lastms`,`r`.`fullContact` AS `fullcontact`,`r`.`regServer` AS `regserver` from (((`pbx`.`sip` `s` join `account`.`user` `u` on(`u`.`id` = `s`.`user_id`)) left join `pbx`.`sipReg` `r` on(`s`.`user_id` = `r`.`userId`)) join `pbx`.`sipConfig` `c`) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85965,7 +85275,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`et`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`et`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`expeditionTruck` `et` on(`rm`.`expeditionTruckFk` = `et`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 0 */; +/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 0 */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86001,7 +85311,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`et`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`et`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`et`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`et`.`id` is null,`c`.`bufferDefault`,`et`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`expeditionTruck` `et` on(`rm`.`expeditionTruckFk` = `et`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */; +/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`rs`.`id` is null,`c`.`bufferDefault`,`rs`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86091,7 +85401,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`et`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`et`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`expeditionTruck` `et` on(`rm`.`expeditionTruckFk` = `et`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */; +/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86498,42 +85808,6 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `exchangeReportSource` --- - -/*!50001 DROP VIEW IF EXISTS `exchangeReportSource`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `exchangeReportSource` AS select `e`.`dated` AS `dated`,cast(sum(`e`.`amountIn`) as decimal(10,2)) AS `amountIn`,cast(sum(`e`.`rateIn`) as decimal(10,4)) AS `rateIn`,cast(sum(`e`.`amountOut`) as decimal(10,2)) AS `amountOut`,cast(sum(`e`.`rateOut`) as decimal(10,4)) AS `rateOut`,cast(sum(`e`.`amountEntry`) as decimal(10,2)) AS `amountEntry`,cast(sum(`e`.`rateEntry`) as decimal(10,4)) AS `rateEntry`,cast(ifnull(`rr`.`value`,`rrc`.`simulatedValue`) as decimal(10,4)) AS `rateECB` from ((`exchangeReportSourcePrevious` `e` left join `referenceRate` `rr` on(`rr`.`dated` = `e`.`dated`)) join `referenceRateConfig` `rrc` on(1)) group by `e`.`dated` order by `e`.`dated` */; -/*!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 `exchangeReportSourcePrevious` --- - -/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `exchangeReportSourcePrevious` AS select `exchangeInsuranceIn`.`dated` AS `dated`,`exchangeInsuranceIn`.`amount` AS `amountIn`,`exchangeInsuranceIn`.`rate` AS `rateIn`,0.00 AS `amountOut`,0.00 AS `rateOut`,0.00 AS `amountEntry`,0.00 AS `rateEntry` from `exchangeInsuranceIn` union all select `exchangeInsuranceOut`.`received` AS `received`,0.00 AS `amountIn`,0.00 AS `ratedIn`,`exchangeInsuranceOut`.`divisa` AS `amountOut`,`exchangeInsuranceOut`.`rate` AS `ratedOut`,0.00 AS `amountEntry`,0.00 AS `rateEntry` from `exchangeInsuranceOut` union all select `exchangeInsuranceEntry`.`dated` AS `dated`,0.00 AS `amountIn`,0.00 AS `ratedIn`,0.00 AS `amountOut`,0.00 AS `ratedOut`,`exchangeInsuranceEntry`.`Dolares` AS `amountEntry`,`exchangeInsuranceEntry`.`rate` AS `rateEntry` from `exchangeInsuranceEntry` */; -/*!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 `expeditionCommon` -- @@ -86547,7 +85821,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionCommon` AS select `et`.`id` AS `truckFk`,`et`.`eta` AS `eta`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`expeditionTruck` `et` left join `routesMonitor` `r` on(`et`.`id` = `r`.`expeditionTruckFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `et`.`eta` >= `util`.`VN_CURDATE`() */; +/*!50001 VIEW `expeditionCommon` AS select `rs`.`id` AS `truckFk`,`rs`.`eta` AS `eta`,ifnull(ucase(`rs`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`roadmapStop` `rs` left join `routesMonitor` `r` on(`rs`.`id` = `r`.`expeditionTruckFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `rs`.`eta` >= `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86565,7 +85839,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionPallet_Print` AS select `et2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`et`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`expeditionTruck` `et` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `et`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `expeditionTruck` `et2` on(`et2`.`id` = `rm`.`expeditionTruckFk`)) group by `ep`.`id`,`t`.`routeFk` */; +/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`expeditionTruckFk`)) group by `ep`.`id`,`t`.`routeFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86583,7 +85857,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `expeditionTruck` `et` on(`et`.`id` = `rm`.`expeditionTruckFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */; +/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86619,7 +85893,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionScan_Monitor` AS select `et`.`id` AS `truckFk`,`et`.`eta` AS `ETD`,`et`.`description` AS `description`,`ep`.`id` AS `palletFk`,`ep`.`position` AS `position`,`ep`.`built` AS `built`,`es`.`id` AS `scanFk`,`es`.`expeditionFk` AS `expeditionFk`,`es`.`scanned` AS `scanned` from ((`expeditionTruck` `et` left join `expeditionPallet` `ep` on(`ep`.`truckFk` = `et`.`id`)) left join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) */; +/*!50001 VIEW `expeditionScan_Monitor` AS select `rs`.`id` AS `truckFk`,`rs`.`eta` AS `ETD`,`rs`.`description` AS `description`,`ep`.`id` AS `palletFk`,`ep`.`position` AS `position`,`ep`.`built` AS `built`,`es`.`id` AS `scanFk`,`es`.`expeditionFk` AS `expeditionFk`,`es`.`scanned` AS `scanned` from ((`roadmapStop` `rs` left join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) left join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86637,7 +85911,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`et`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `expeditionTruck` `et` on(`et`.`id` = `rm`.`expeditionTruckFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */; +/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`rs`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86655,7 +85929,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`et`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `expeditionTruck` `et` on(`et`.`id` = `rm`.`expeditionTruckFk`)) where `e`.`id` is null and `et`.`eta` > `util`.`VN_CURDATE`() */; +/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`rs`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) where `e`.`id` is null and `rs`.`eta` > `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -86678,6 +85952,24 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `expeditionTruck` +-- + +/*!50001 DROP VIEW IF EXISTS `expeditionTruck`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_unicode_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ +/*!50001 VIEW `expeditionTruck` AS select `rs`.`id` AS `id`,`rs`.`roadmapFk` AS `roadmapFk`,`rs`.`warehouseFk` AS `warehouseFk`,`rs`.`eta` AS `eta`,`rs`.`description` AS `description`,`rs`.`bufferFk` AS `bufferFk`,`rs`.`created` AS `created`,`rs`.`userFk` AS `userFk` from `roadmapStop` `rs` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `expeditionTruck_Control` -- @@ -86727,7 +86019,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`et`.`description` AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk`,max(`e`.`lastPacked`) AS `lastPacked` from (`expeditionCommon` `e` left join `expeditionTruck` `et` on(`et`.`id` = `e`.`expeditionTruckFk`)) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`palletFk` */; +/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`rs`.`description` AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk`,max(`e`.`lastPacked`) AS `lastPacked` from (`expeditionCommon` `e` left join `roadmapStop` `rs` on(`rs`.`id` = `e`.`expeditionTruckFk`)) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`palletFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -87501,7 +86793,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `routesControl` AS select `t`.`routeFk` AS `routeFk`,count(`e`.`id`) AS `expeditions`,count(`es`.`id`) AS `scanned`,count(distinct `es`.`palletFk`) AS `pallets`,max(`es`.`scanned`) AS `lastScanned`,max(`et`.`description`) AS `description`,max(`et`.`eta`) AS `eta` from ((((`ticket` `t` join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) left join `expeditionPallet` `ep` on(`ep`.`id` = `es`.`palletFk`)) left join `expeditionTruck` `et` on(`et`.`id` = `ep`.`truckFk`)) where `t`.`shipped` >= `util`.`VN_CURDATE`() and `t`.`routeFk` <> 0 group by `t`.`routeFk` order by max(`et`.`eta`) */; +/*!50001 VIEW `routesControl` AS select `t`.`routeFk` AS `routeFk`,count(`e`.`id`) AS `expeditions`,count(`es`.`id`) AS `scanned`,count(distinct `es`.`palletFk`) AS `pallets`,max(`es`.`scanned`) AS `lastScanned`,max(`rs`.`description`) AS `description`,max(`rs`.`eta`) AS `eta` from ((((`ticket` `t` join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) left join `expeditionPallet` `ep` on(`ep`.`id` = `es`.`palletFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `ep`.`truckFk`)) where `t`.`shipped` >= `util`.`VN_CURDATE`() and `t`.`routeFk` <> 0 group by `t`.`routeFk` order by max(`rs`.`eta`) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -87609,7 +86901,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `saleVolume` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,round(`ic`.`cm3delivery` * `s`.`quantity` / 1000,0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `volume`,`s`.`quantity` * `ic`.`grams` / 1000 AS `physicalWeight`,`s`.`quantity` * `ic`.`cm3delivery` * greatest(`ic`.`grams` / `ic`.`cm3delivery`,`vc`.`aerealVolumetricDensity`) / 1000000 AS `weight`,`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `physicalVolume`,`s`.`quantity` * `ic`.`cm3delivery` * ifnull(`t`.`zonePrice` - ifnull(`t`.`zoneBonus`,0),`z`.`price` - `z`.`bonus`) / (`vc`.`standardFlowerBox` * 1000) * `z`.`inflation` AS `freight`,`t`.`zoneFk` AS `zoneFk`,`t`.`clientFk` AS `clientFk`,`s`.`isPicked` AS `isPicked`,`s`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100 AS `eurosValue`,`i`.`itemPackingTypeFk` AS `itemPackingTypeFk` from (((((`sale` `s` join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) join `volumeConfig` `vc`) join `itemCost` `ic` on(`ic`.`itemFk` = `s`.`itemFk` and `ic`.`warehouseFk` = `t`.`warehouseFk`)) where `s`.`quantity` > 0 */; +/*!50001 VIEW `saleVolume` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,round(`ic`.`cm3delivery` * `s`.`quantity` / 1000,0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `volume`,`s`.`quantity` * `ic`.`grams` / 1000 AS `physicalWeight`,`s`.`quantity` * `ic`.`cm3delivery` * greatest(`ic`.`grams` / `ic`.`cm3delivery`,`vc`.`aerealVolumetricDensity`) / 1000000 AS `weight`,`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `physicalVolume`,`s`.`quantity` * `ic`.`cm3delivery` * ifnull(`t`.`zonePrice` - ifnull(`t`.`zoneBonus`,0),`z`.`price` - `z`.`bonus`) / (`vc`.`standardFlowerBox` * 1000) * `z`.`inflation` AS `freight`,`t`.`zoneFk` AS `zoneFk`,`t`.`clientFk` AS `clientFk`,`s`.`isPicked` AS `isPicked`,`s`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100 AS `eurosValue`,`i`.`itemPackingTypeFk` AS `itemPackingTypeFk` from (((((`sale` `s` join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `ticket` `t` on(`t`.`id` = `s`.`ticketFk`)) join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) join `volumeConfig` `vc`) join `itemCost` `ic` FORCE INDEX (PRIMARY) on(`ic`.`itemFk` = `s`.`itemFk` and `ic`.`warehouseFk` = `t`.`warehouseFk`)) where `s`.`quantity` > 0 */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -87627,7 +86919,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `saleVolume_Today_VNH` AS select `t`.`nickname` AS `Cliente`,`p`.`name` AS `Provincia`,`c`.`country` AS `Pais`,cast(sum(`sv`.`volume`) as decimal(5,1)) AS `volume` from (((((`saleVolume` `sv` join `ticket` `t` on(`t`.`id` = `sv`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) join `country` `c` on(`c`.`id` = `p`.`countryFk`)) join `warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) where `w`.`name` = 'VNH' and `t`.`shipped` between `util`.`VN_CURDATE`() and `util`.`dayend`(`util`.`VN_CURDATE`()) group by `t`.`nickname`,`p`.`name` */; +/*!50001 VIEW `saleVolume_Today_VNH` AS select `t`.`nickname` AS `Cliente`,`p`.`name` AS `Provincia`,`c`.`name` AS `Pais`,cast(sum(`sv`.`volume`) as decimal(5,1)) AS `volume` from (((((`saleVolume` `sv` join `ticket` `t` on(`t`.`id` = `sv`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) join `country` `c` on(`c`.`id` = `p`.`countryFk`)) join `warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) where `w`.`name` = 'VNH' and `t`.`shipped` between `util`.`VN_CURDATE`() and `util`.`dayend`(`util`.`VN_CURDATE`()) group by `t`.`nickname`,`p`.`name` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88276,12 +87568,12 @@ USE `vn2008`; /*!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 = utf8mb3 */; -/*!50001 SET character_set_results = utf8mb3 */; -/*!50001 SET collation_connection = utf8mb3_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Compres` AS select `c`.`id` AS `Id_Compra`,`c`.`entryFk` AS `Id_Entrada`,`c`.`itemFk` AS `Id_Article`,`c`.`buyingValue` AS `Costefijo`,`c`.`quantity` AS `Cantidad`,`c`.`packagingFk` AS `Id_Cubo`,`c`.`stickers` AS `Etiquetas`,`c`.`freightValue` AS `Portefijo`,`c`.`packageValue` AS `Embalajefijo`,`c`.`comissionValue` AS `Comisionfija`,`c`.`packing` AS `Packing`,`c`.`grouping` AS `grouping`,`c`.`groupingMode` AS `caja`,`c`.`location` AS `Nicho`,`c`.`price1` AS `Tarifa1`,`c`.`price2` AS `Tarifa2`,`c`.`price3` AS `Tarifa3`,`c`.`minPrice` AS `PVP`,`c`.`printedStickers` AS `Vida`,`c`.`isChecked` AS `punteo`,`c`.`ektFk` AS `buy_edi_id`,`c`.`created` AS `odbc_date`,`c`.`isIgnored` AS `Novincular`,`c`.`isPickedOff` AS `isPickedOff`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`weight` AS `weight`,`c`.`dispatched` AS `dispatched`,`c`.`containerFk` AS `container_id`,`c`.`itemOriginalFk` AS `itemOriginalFk` from `vn`.`buy` `c` */; +/*!50001 VIEW `Compres` AS select `c`.`id` AS `Id_Compra`,`c`.`entryFk` AS `Id_Entrada`,`c`.`itemFk` AS `Id_Article`,`c`.`buyingValue` AS `Costefijo`,`c`.`quantity` AS `Cantidad`,`c`.`packagingFk` AS `Id_Cubo`,`c`.`stickers` AS `Etiquetas`,`c`.`freightValue` AS `Portefijo`,`c`.`packageValue` AS `Embalajefijo`,`c`.`comissionValue` AS `Comisionfija`,`c`.`packing` AS `Packing`,`c`.`grouping` AS `grouping`,`c`.`groupingMode` AS `caja`,`c`.`location` AS `Nicho`,`c`.`price1` AS `Tarifa1`,`c`.`price2` AS `Tarifa2`,`c`.`price3` AS `Tarifa3`,`c`.`minPrice` AS `PVP`,`c`.`printedStickers` AS `Vida`,`c`.`isChecked` AS `punteo`,`c`.`ektFk` AS `buy_edi_id`,`c`.`created` AS `odbc_date`,`c`.`isIgnored` AS `Novincular`,`c`.`isPickedOff` AS `isPickedOff`,`c`.`workerFk` AS `Id_Trabajador`,`c`.`weight` AS `weight`,`c`.`dispatched` AS `dispatched`,`c`.`itemOriginalFk` AS `itemOriginalFk` from `vn`.`buy` `c` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88569,7 +87861,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Paises` AS select `c`.`id` AS `Id`,`c`.`country` AS `Pais`,`c`.`CEE` AS `CEE`,`c`.`isUeeMember` AS `isUeeMember`,`c`.`code` AS `Codigo`,`c`.`currencyFk` AS `Id_Moneda`,`c`.`geoFk` AS `geoFk`,`c`.`ibanLength` AS `ibanLength`,`c`.`hasDailyInvoice` AS `hasDailyInvoice` from `vn`.`country` `c` */; +/*!50001 VIEW `Paises` AS select `c`.`id` AS `Id`,`c`.`name` AS `Pais`,`c`.`CEE` AS `CEE`,`c`.`isUeeMember` AS `isUeeMember`,`c`.`code` AS `Codigo`,`c`.`currencyFk` AS `Id_Moneda`,`c`.`geoFk` AS `geoFk`,`c`.`ibanLength` AS `ibanLength`,`c`.`hasDailyInvoice` AS `hasDailyInvoice` from `vn`.`country` `c` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88605,7 +87897,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Proveedores` AS select `s`.`id` AS `Id_Proveedor`,`s`.`name` AS `Proveedor`,`s`.`account` AS `cuenta`,`s`.`countryFk` AS `pais_id`,`s`.`nif` AS `NIF`,`s`.`isFarmer` AS `Agricola`,`s`.`phone` AS `Telefono`,`s`.`retAccount` AS `cuentaret`,`s`.`commission` AS `ComisionProveedor`,`s`.`created` AS `odbc_time`,`s`.`postcodeFk` AS `postcode_id`,`s`.`isActive` AS `active`,`s`.`street` AS `Domicilio`,`s`.`city` AS `Localidad`,`s`.`provinceFk` AS `province_id`,`s`.`postCode` AS `codpos`,`s`.`payMethodFk` AS `pay_met_id`,`s`.`payDemFk` AS `pay_dem_id`,`s`.`nickname` AS `Alias`,`s`.`isOfficial` AS `oficial`,`s`.`workerFk` AS `workerFk`,`s`.`payDay` AS `pay_day`,`s`.`isReal` AS `serious`,`s`.`note` AS `notas`,`s`.`taxTypeSageFk` AS `taxTypeSageFk`,`s`.`withholdingSageFk` AS `withholdingSageFk`,`s`.`isTrucker` AS `isTrucker`,`s`.`transactionTypeSageFk` AS `transactionTypeSageFk`,`s`.`supplierActivityFk` AS `supplierActivityFk`,`s`.`healthRegister` AS `healthRegister`,`s`.`isPayMethodChecked` AS `isPayMethodChecked` from `vn`.`supplier` `s` */; +/*!50001 VIEW `Proveedores` AS select `s`.`id` AS `Id_Proveedor`,`s`.`name` AS `Proveedor`,`s`.`account` AS `cuenta`,`s`.`countryFk` AS `pais_id`,`s`.`nif` AS `NIF`,`s`.`phone` AS `Telefono`,`s`.`retAccount` AS `cuentaret`,`s`.`commission` AS `ComisionProveedor`,`s`.`created` AS `odbc_time`,`s`.`postcodeFk` AS `postcode_id`,`s`.`isActive` AS `active`,`s`.`street` AS `Domicilio`,`s`.`city` AS `Localidad`,`s`.`provinceFk` AS `province_id`,`s`.`postCode` AS `codpos`,`s`.`payMethodFk` AS `pay_met_id`,`s`.`payDemFk` AS `pay_dem_id`,`s`.`nickname` AS `Alias`,`s`.`isOfficial` AS `oficial`,`s`.`workerFk` AS `workerFk`,`s`.`payDay` AS `pay_day`,`s`.`isReal` AS `serious`,`s`.`note` AS `notas`,`s`.`taxTypeSageFk` AS `taxTypeSageFk`,`s`.`withholdingSageFk` AS `withholdingSageFk`,`s`.`isTrucker` AS `isTrucker`,`s`.`transactionTypeSageFk` AS `transactionTypeSageFk`,`s`.`supplierActivityFk` AS `supplierActivityFk`,`s`.`healthRegister` AS `healthRegister`,`s`.`isPayMethodChecked` AS `isPayMethodChecked` from `vn`.`supplier` `s` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -89037,7 +88329,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `albaran` AS select `dn`.`id` AS `albaran_id`,`dn`.`ref` AS `ref`,`dn`.`note` AS `note`,`dn`.`shipped` AS `fecha`,`dn`.`landed` AS `fecha_entrega`,`dn`.`amount` AS `valor`,`dn`.`supplierFk` AS `Id_Proveedor`,`dn`.`companyFk` AS `empresa_id`,`dn`.`warehouseFk` AS `warehouse_id`,`dn`.`stateFk` AS `albaran_state_id`,`dn`.`workerFk` AS `Id_Trabajador`,`dn`.`supervisorFk` AS `Id_Responsable`,`dn`.`departmentFk` AS `department_id`,`dn`.`invoiceInFk` AS `recibida_id`,`dn`.`farmingFk` AS `farmingFk` from `vn`.`deliveryNote` `dn` */; +/*!50001 VIEW `albaran` AS select `dn`.`id` AS `albaran_id`,`dn`.`ref` AS `ref`,`dn`.`note` AS `note`,`dn`.`shipped` AS `fecha`,`dn`.`landed` AS `fecha_entrega`,`dn`.`amount` AS `valor`,`dn`.`supplierFk` AS `Id_Proveedor`,`dn`.`companyFk` AS `empresa_id`,`dn`.`warehouseFk` AS `warehouse_id`,`dn`.`stateFk` AS `albaran_state_id`,`dn`.`workerFk` AS `Id_Trabajador`,`dn`.`supervisorFk` AS `Id_Responsable`,`dn`.`departmentFk` AS `department_id`,`dn`.`invoiceInFk` AS `recibida_id` from `vn`.`deliveryNote` `dn` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -90563,4 +89855,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-05-14 6:26:25 +-- Dump completed on 2024-05-28 6:58:24 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index 251e46260..fd1042138 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -3789,7 +3789,7 @@ DELIMITER ;; BEFORE INSERT ON `country` FOR EACH ROW BEGIN - SET NEW.geoFk = zoneGeo_new('country', NEW.country, NULL); + SET NEW.geoFk = zoneGeo_new('country', NEW.name, NULL); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3811,14 +3811,17 @@ DELIMITER ;; BEGIN UPDATE sage.Naciones SET countryFk = NEW.id - WHERE Nacion = NEW.country; + WHERE Nacion = NEW.name; IF ROW_COUNT() = 0 THEN CALL mail_insert( 'cau@verdnatura.es', NULL, 'Actualizar tabla sage.Naciones', - CONCAT('Se ha insertado un nuevo país en la tabla vn.conuntry. Para el correcto funcionamiento del sistema \n\t\t\t\tde contabilidad es necesario actualizar la columna sage.Naciones.countryFk con el valor del nuevo país. \n\t\t\t Hay que buscar el nuevo país: ', NEW.country, ' en la tabla sage.Naciones y actualizar el campo sage.Naciones.countryFk con el valor ', NEW.id) + CONCAT('Se ha insertado un nuevo país en la tabla vn.conuntry. + Para el correcto funcionamiento del sistema \n\t\t\t\tde contabilidad es necesario actualizar la columna + sage.Naciones.countryFk con el valor del nuevo país. \n\t\t\t Hay que buscar el nuevo país: ', NEW.name, + ' en la tabla sage.Naciones y actualizar el campo sage.Naciones.countryFk con el valor ', NEW.id) ); END IF; END */;; @@ -3862,8 +3865,8 @@ DELIMITER ;; AFTER UPDATE ON `country` FOR EACH ROW BEGIN - IF !(OLD.country <=> NEW.country) THEN - UPDATE zoneGeo SET `name` = NEW.country + IF !(OLD.name <=> NEW.name) THEN + UPDATE zoneGeo SET `name` = NEW.name WHERE id = NEW.geoFk; END IF; END */;; @@ -4325,10 +4328,32 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionUser_afterInsert` + AFTER INSERT ON `deviceProductionUser` + FOR EACH ROW +BEGIN + CALL worker_checkMultipleDevice(NEW.userFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionUser_beforeUpdate` BEFORE UPDATE ON `deviceProductionUser` FOR EACH ROW BEGIN + + CALL worker_checkMultipleDevice(NEW.userFk); SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -5060,50 +5085,6 @@ BEGIN SET e.stateTypeFk = NEW.typeFk WHERE e.id = NEW.expeditionFk; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionTruck_beforeInsert` - BEFORE INSERT ON `expeditionTruck` - FOR EACH ROW -BEGIN - - SET NEW.description = UCASE(NEW.description); - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionTruck_beforeUpdate` - BEFORE UPDATE ON `expeditionTruck` - FOR EACH ROW -BEGIN - - SET NEW.description = UCASE(NEW.description); - END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6796,94 +6777,95 @@ DELIMITER ;; BEFORE INSERT ON `payment` FOR EACH ROW BEGIN - DECLARE cuenta_banco,cuenta_proveedor DOUBLE; - DECLARE vNewBookEntry INT; - DECLARE bolCASH BOOLEAN; - DECLARE isSupplierActive BOOLEAN; + DECLARE vBankAccount DOUBLE; + DECLARE vSupplierAccount DOUBLE; + DECLARE vNewBookEntry INT; + DECLARE vIsCash BOOLEAN; + DECLARE vIsSupplierActive BOOLEAN; - -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH - SELECT (at2.code = 'cash') INTO bolCASH - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; + -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH + SELECT (at2.code = 'cash') INTO vIsCash + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; - IF bolCASH THEN - - SELECT account INTO cuenta_banco - FROM accounting - WHERE id = NEW.bankFk; - - SELECT account INTO cuenta_proveedor - FROM supplier - WHERE id = NEW.supplierFk; + IF vIsCash THEN + SELECT account INTO vBankAccount + FROM accounting + WHERE id = NEW.bankFk; - CALL ledger_next(vNewBookEntry); - - INSERT INTO XDiario ( ASIEN, - FECHA, - SUBCTA, - CONTRA, - CONCEPTO, - EURODEBE, - EUROHABER, - empresa_id) - SELECT vNewBookEntry, - NEW.received, - SUBCTA, - CONTRA, - NEW.concept, - EURODEBE, - EUROHABER, - NEW.companyFk - FROM ( SELECT cuenta_banco SUBCTA, - cuenta_proveedor CONTRA, - 0 EURODEBE, - NEW.amount + NEW.bankingFees EUROHABER - UNION ALL - SELECT cuenta_proveedor SUBCTA, - cuenta_banco CONTRA, - NEW.amount EURODEBE, - 0 EUROHABER) gf; - - IF NEW.bankingFees <> 0 THEN - INSERT INTO XDiario ( ASIEN, - FECHA, - SUBCTA, - CONTRA, - CONCEPTO, - EURODEBE, - EUROHABER, - empresa_id) - SELECT vNewBookEntry, - NEW.received, - IF(c.id = 1,6260000002, - IF(CEE = 1,6260000003,6260000004)), - cuenta_banco, - NEW.concept, - NEW.bankingFees, - 0, - NEW.companyFk - FROM supplier s - JOIN country c ON s.countryFk = c.id - WHERE s.id = NEW.supplierFk; - END IF; - END IF; - - SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); - - SELECT isActive INTO isSupplierActive + SELECT account INTO vSupplierAccount FROM supplier WHERE id = NEW.supplierFk; - - IF isSupplierActive = FALSE THEN - CALL util.throw('SUPPLIER_INACTIVE'); - END IF; - - IF ISNULL(NEW.workerFk) THEN - SET NEW.workerFk = account.myUser_getId(); - END IF; - - END */;; + + CALL ledger_next(YEAR(NEW.received), NEW.companyFk, vNewBookEntry); + + INSERT INTO XDiario ( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + CONCEPTO, + EURODEBE, + EUROHABER, + empresa_id) + SELECT vNewBookEntry, + NEW.received, + SUBCTA, + CONTRA, + NEW.concept, + EURODEBE, + EUROHABER, + NEW.companyFk + FROM (SELECT vBankAccount SUBCTA, + vSupplierAccount CONTRA, + 0 EURODEBE, + NEW.amount + NEW.bankingFees EUROHABER + UNION ALL + SELECT vSupplierAccount SUBCTA, + vBankAccount CONTRA, + NEW.amount EURODEBE, + 0 EUROHABER) gf; + + IF NEW.bankingFees <> 0 THEN + INSERT INTO XDiario ( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + CONCEPTO, + EURODEBE, + EUROHABER, + empresa_id) + SELECT vNewBookEntry, + NEW.received, + IF(c.id = 1,6260000002, + IF(CEE = 1,6260000003,6260000004)), + vBankAccount, + NEW.concept, + NEW.bankingFees, + 0, + NEW.companyFk + FROM supplier s + JOIN country c ON s.countryFk = c.id + WHERE s.id = NEW.supplierFk; + END IF; + END IF; + + SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); + + SELECT isActive INTO vIsSupplierActive + FROM supplier + WHERE id = NEW.supplierFk; + + IF vIsSupplierActive = FALSE THEN + CALL util.throw('SUPPLIER_INACTIVE'); + END IF; + + IF ISNULL(NEW.workerFk) THEN + SET NEW.workerFk = account.myUser_getId(); + END IF; +END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; @@ -7472,6 +7454,48 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionTruck_beforeInsert` + BEFORE INSERT ON `roadmapStop` FOR EACH ROW +BEGIN + + SET NEW.description = UCASE(NEW.description); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionTruck_beforeUpdate` + BEFORE UPDATE ON `roadmapStop` FOR EACH ROW +BEGIN + + SET NEW.description = UCASE(NEW.description); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_beforeInsert` BEFORE INSERT ON `route` FOR EACH ROW @@ -8961,6 +8985,8 @@ BEGIN UPDATE expedition SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; + + CALL ticket_doCmr(NEW.id); END IF; END */;; DELIMITER ; @@ -9318,7 +9344,6 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - CALL ticketRefund_beforeUpsert(NEW.refundTicketFk, NEW.originalTicketFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9339,7 +9364,6 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - CALL ticketRefund_beforeUpsert(NEW.refundTicketFk, NEW.originalTicketFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9655,11 +9679,6 @@ BEGIN `changedModel` = 'TicketTracking', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - - CALL util.debugAdd('deletedState', - CONCAT('interFk: ', OLD.id, - ' ticketFk: ', OLD.ticketFk, - ' stateFk: ', OLD.stateFk)); SELECT i.ticketFk, i.id, s.`name` INTO vTicketFk, vTicketTrackingFk, vStateName @@ -10805,4 +10824,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-05-14 6:26:46 +-- Dump completed on 2024-05-28 6:58:42 diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index fd940d8a6..562ea02d8 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -129,7 +129,7 @@ INSERT INTO vn.itemShelving (id,itemFk,visible,shelvingFk,`grouping`,packing,pac INSERT INTO vn.beach (code,warehouseFk) VALUES ('TEST',1); -INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,expeditionTruckFk) VALUES +INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,roadmapStopFk) VALUES (1,'TEST','TEST',1.0,1); /* #5483 INSERT INTO vn.ticket (clientFk, warehouseFk, shipped, nickname, refFk, addressFk, workerFk, observations, isSigned, isLabeled, isPrinted, packages, location, `hour`, created, isBlocked, solution, routeFk, priority, hasPriority, companyFk, agencyModeFk, landed, isBoxed, isDeleted, zoneFk, zonePrice, zoneBonus, totalWithVat, totalWithoutVat, weight) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 3e6edf07d..30f1ceb5e 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -762,7 +762,12 @@ INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeF (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), - (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL); + (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (34, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (37, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1110, 'Deadpool swords', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); + INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES (1, 11, 1, 'ready'), @@ -808,7 +813,10 @@ INSERT INTO `vn`.`ticketTracking`(`ticketFk`, `stateFk`, `userFk`, `created`) (21, 1, 19, DATE_ADD(util.VN_NOW(), INTERVAL +1 MONTH)), (22, 1, 19, DATE_ADD(util.VN_NOW(), INTERVAL +1 MONTH)), (23, 16, 21, util.VN_NOW()), - (24, 16, 21, util.VN_NOW()); + (24, 16, 21, util.VN_NOW()), + (34, 14, 49, util.VN_NOW()), + (35, 14, 18, util.VN_NOW()), + (36, 14, 18, util.VN_NOW()); INSERT INTO `vn`.`deliveryPoint` (`id`, `name`, `ubication`) VALUES @@ -1068,7 +1076,10 @@ INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `pric (37, 4, 31, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (36, 4, 30, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (38, 2, 32, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH)), - (39, 1, 32, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE()); + (39, 1, 32, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE()), + (40, 2, 34, 'Melee weapon combat fist 15cm', 10.00, 3.91, 0, 0, 0, util.VN_CURDATE()), + (41, 2, 35, 'Melee weapon combat fist 15cm', 8.00, 3.01, 0, 0, 0, util.VN_CURDATE()), + (42, 2, 36, 'Melee weapon combat fist 15cm', 6.00, 2.50, 0, 0, 0, util.VN_CURDATE()); INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) VALUES @@ -1205,11 +1216,11 @@ INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) (32, 36, -92.324), (32, 39, 0.994); -INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `visible`, `grouping`, `packing`, `userFk`) +INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `visible`, `grouping`, `packing`,`buyFk`, `userFk`) VALUES - (2, 'GVC', 1, 1, 1, 1106), - (4, 'HEJ', 1, 1, 1, 1106), - (1, 'UXN', 2, 12, 12, 1106); + (2, 'GVC', 1, 1, 1, 2,1106), + (4, 'HEJ', 1, 1, 1, NULL,1106), + (1, 'UXN', 2, 12, 12, NULL,1106); INSERT INTO `vn`.`itemShelvingSale` (`itemShelvingFk`, `saleFk`, `quantity`, `created`, `userFk`) VALUES @@ -1247,14 +1258,20 @@ INSERT INTO `vn`.`operator` (`workerFk`, `numberOfWagons`, `trainFk`, `itemPacki INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`, `trainFk`) VALUES (1, 1106, 5, DATE_ADD(util.VN_CURDATE(),INTERVAL +1 DAY), 1), - (2, 1106, 14, util.VN_CURDATE(), 1); + (2, 1106, 14, util.VN_CURDATE(), 1), + (4, 49, 5, util.VN_CURDATE(), 1), + (5, 18, 5, util.VN_CURDATE(), 1), + (6, 18, 5, util.VN_CURDATE(), 1); INSERT INTO `vn`.`ticketCollection`(`ticketFk`, `collectionFk`, `level`) VALUES (1, 1, 1), (2, 1, NULL), (3, 2, NULL), - (23, 1, NULL); + (23, 1, NULL), + (34, 4, 1), + (35, 5, 1), + (8, 6, 1); INSERT INTO `vn`.`genus`(`id`, `name`) VALUES @@ -2549,18 +2566,18 @@ INSERT INTO `vn`.`duaEntry` (`duaFk`, `entryFk`, `value`, `customsValue`, `euroV (7, 7, 1.00, 1.00, 1.00), (8, 8, 1.00, 1.00, 1.00); -REPLACE INTO `vn`.`invoiceIn`(`id`, `serialNumber`,`serial`, `supplierFk`, `issued`, `created`, `supplierRef`, `isBooked`, `companyFk`, `docFk`) +REPLACE INTO `vn`.`invoiceIn`(`id`, `serialNumber`,`serial`, `supplierFk`, `issued`, `created`, `supplierRef`, `isBooked`, `companyFk`, `docFk`, `bookEntried`) VALUES - (1, 1001, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1234, 0, 442, 1), - (2, 1002, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1235, 0, 442, 1), - (3, 1003, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1236, 0, 442, 1), - (4, 1004, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1237, 0, 442, 1), - (5, 1005, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1238, 0, 442, 1), - (6, 1006, 'R', 2, util.VN_CURDATE(), util.VN_CURDATE(), 1239, 0, 442, 1), - (7, 1007, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1240, 0, 442, 1), - (8, 1008, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1241, 0, 442, 1), - (9, 1009, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1242, 0, 442, 1), - (10, 1010, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1243, 0, 442, 1); + (1, 1001, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1234, 0, 442, 1,util.VN_CURDATE()), + (2, 1002, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1235, 0, 442, 1,util.VN_CURDATE()), + (3, 1003, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1236, 0, 442, 1,util.VN_CURDATE()), + (4, 1004, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1237, 0, 442, 1,util.VN_CURDATE()), + (5, 1005, 'R', 1, util.VN_CURDATE(), util.VN_CURDATE(), 1238, 0, 442, 1,util.VN_CURDATE()), + (6, 1006, 'R', 2, util.VN_CURDATE(), util.VN_CURDATE(), 1239, 0, 442, 1,util.VN_CURDATE()), + (7, 1007, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1240, 0, 442, 1,util.VN_CURDATE()), + (8, 1008, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1241, 0, 442, 1,util.VN_CURDATE()), + (9, 1009, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1242, 0, 442, 1,util.VN_CURDATE()), + (10, 1010, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1243, 0, 442, 1,util.VN_CURDATE()); INSERT INTO `vn`.`invoiceInConfig` (`id`, `retentionRate`, `retentionName`, `sageFarmerWithholdingFk`, `daysAgo`) VALUES @@ -2670,13 +2687,20 @@ INSERT INTO `vn`.`zoneAgencyMode`(`id`, `agencyModeFk`, `zoneFk`) (3, 6, 5), (4, 7, 1); +INSERT INTO `vn`.`roadmapAddress` (`addressFk`) + VALUES + (1), + (2), + (3), + (4); + INSERT INTO `vn`.`roadmap` (`id`, `name`, `tractorPlate`, `trailerPlate`, `phone`, `supplierFk`, `etd`, `observations`, `userFk`, `price`, `driverName`) VALUES - (1, 'val-algemesi', 'RE-001', 'PO-001', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'), - (2, 'alg-valencia', 'RE-002', 'PO-002', '111111111', 1, util.VN_NOW(), 'test observation', 1, 20, 'Robin'), - (3, 'alz-algemesi', 'RE-003', 'PO-003', '222222222', 2, DATE_ADD(util.VN_NOW(), INTERVAL 2 DAY), 'observations...', 2, 25, 'Driverman'); + (1, 'val-algemesi', '1234-BCD', '9876-BCD', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'), + (2, 'alg-valencia', '2345-CDF', '8765-BCD', '111111111', 1, util.VN_NOW(), 'test observation', 1, 20, 'Robin'), + (3, 'alz-algemesi', '3456-DFG', '7654-BCD', '222222222', 2, DATE_ADD(util.VN_NOW(), INTERVAL 2 DAY), 'observations...', 2, 25, 'Driverman'); -INSERT INTO `vn`.`expeditionTruck` (`id`, `roadmapFk`, `warehouseFk`, `eta`, `description`, `userFk`) +INSERT INTO `vn`.`roadmapStop` (`id`, `roadmapFk`, `addressFk`, `eta`, `description`, `userFk`) VALUES (1, 1, 1, DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY), 'Best truck in fleet', 1), (2, 1, 2, DATE_ADD(util.VN_NOW(), INTERVAL '1 2' DAY_HOUR), 'Second truck in fleet', 1), @@ -3705,7 +3729,8 @@ INSERT IGNORE INTO vn.saleGroup SET id = 4, userFk = 1, parkingFk = 9, - sectorFk = 9992; + sectorFk = 9992, + ticketFk = 36; INSERT IGNORE INTO vn.sectorCollectionSaleGroup SET id = 9999, @@ -3788,7 +3813,46 @@ INSERT INTO vn.workerTeam(id, team, workerFk) VALUES (8, 1, 19); -INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) +INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) VALUES(100, 'workCenterOne', 1, NULL, 1, 'gotham', NULL, NULL); -UPDATE vn.locker SET workerFk = 1110 WHERE id = 147; \ No newline at end of file +INSERT INTO `vn`.`locker` (code, gender, workerFk) VALUES + ('1M', 'M', 1), + ('2M', 'M', 9), + ('3M', 'M', NULL), + ('4M', 'M', NULL), + ('1F', 'F', 1110), + ('2F', 'F', NULL), + ('3F', 'F', NULL), + ('4F', 'F', NULL); + +INSERT INTO `vn`.`ledgerCompany` SET + fiscalYear = YEAR(util.VN_CURDATE()), + bookEntry = 2; + +INSERT INTO `vn`.`ledgerConfig` SET + maxTolerance = 0.01; + +INSERT INTO vn.sectorCollection + SET id = 2, + userFk = 18, + sectorFk = 1; + +INSERT INTO vn.sectorCollectionSaleGroup + SET id = 8, + sectorCollectionFk = 2, + saleGroupFk = 4; + +INSERT INTO vn.saleGroup (userFk, parkingFk, sectorFk, ticketFk) + VALUES + (1, 1, 1, 37); + +INSERT INTO vn.sectorCollection + SET id = 3, + userFk = 18, + sectorFk = 1; + +INSERT INTO vn.sectorCollectionSaleGroup + SET id = 9, + sectorCollectionFk = 3, + saleGroupFk = 6; \ No newline at end of file diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index ae87e15a2..3cf4bf8dc 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -48,7 +48,7 @@ BEGIN -- Marcamos para no repetir UPDATE vn.claimEnd ce JOIN vn.claim c ON c.id = ce.claimFk - SET c.isChargedToMana = TRUE + SET ce.isGreuge = TRUE WHERE ce.claimDestinationFk NOT IN (1,5) AND NOT ce.isGreuge AND c.claimStateFk = 3; @@ -65,11 +65,12 @@ BEGIN JOIN vn.ticketLastState ts ON ts.ticketFk = t.id JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk JOIN vn.state st ON st.id = tt.stateFk + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE sc.componentFk = 17 AND sc.isGreuge = 0 AND t.shipped >= '2016-10-01' AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= 3; + AND st.alertLevel >= al.id; DELETE g.* FROM vn.greuge g diff --git a/db/routines/dipole/procedures/expedition_add.sql b/db/routines/dipole/procedures/expedition_add.sql index e224cd2d2..70bc7930e 100644 --- a/db/routines/dipole/procedures/expedition_add.sql +++ b/db/routines/dipole/procedures/expedition_add.sql @@ -46,7 +46,7 @@ BEGIN JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p ON p.id = a.provinceFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk LEFT JOIN vn.beach b ON b.code = rm.beachFk LEFT JOIN vn.`zone`z ON z.id = t.zoneFk JOIN vn.agencyMode am ON t.agencyModeFk = am.id diff --git a/db/routines/edi/procedures/ekt_scan.sql b/db/routines/edi/procedures/ekt_scan.sql index b0b75a6a7..0cf8bb466 100644 --- a/db/routines/edi/procedures/ekt_scan.sql +++ b/db/routines/edi/procedures/ekt_scan.sql @@ -23,42 +23,39 @@ BEGIN DECLARE vXtraLongAgj INT; DECLARE vDefaultKlo INT; - SELECT - ec.usefulAuctionLeftSegmentLength, - ec.standardBarcodeLength, - ec.floridayBarcodeLength, - ec.floramondoBarcodeLength, - ec.defaultKlo - INTO - vUsefulAuctionLeftSegmentLength, + SELECT usefulAuctionLeftSegmentLength, + standardBarcodeLength, + floridayBarcodeLength, + floramondoBarcodeLength, + defaultKlo + INTO vUsefulAuctionLeftSegmentLength, vStandardBarcodeLength, vFloridayBarcodeLength, vFloramondoBarcodeLength, vDefaultKlo - FROM edi.ektConfig ec; + FROM ektConfig; - DROP TEMPORARY TABLE IF EXISTS tmp.ekt; - CREATE TEMPORARY TABLE tmp.ekt + CREATE OR REPLACE TEMPORARY TABLE tmp.ekt ENGINE = MEMORY SELECT id ektFk FROM ekt LIMIT 0; - CASE + CASE WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e + FROM ektRecent e WHERE e.cps = vBarcode OR e.batchNumber = vBarcode; WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN INSERT INTO tmp.ekt SELECT e.id - FROM edi.ektRecent e + FROM ektRecent e WHERE e.pro = MID(vBarcode,2,6) - AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5); + AND CAST(e.ptd AS SIGNED) = MID(vBarcode, 8, 5); ELSE - SET vBarcode = LPAD(vBarcode,vStandardBarcodeLength,'0'); + SET vBarcode = LPAD(vBarcode, vStandardBarcodeLength, '0'); SET vAuction = MID(vBarcode, 1, 3); SET vKlo = MID(vBarcode, 4, 2); SET vFec = MAKEDATE(YEAR(util.VN_CURDATE()), MID(vBarcode, 6, 3)); @@ -69,21 +66,23 @@ BEGIN -- Clásico de subasta -- Trade standard -- Trade que construye como la subasta - -- Trade como el anterior pero sin trade code + -- Trade como el anterior pero sin trade code INSERT INTO tmp.ekt SELECT id FROM ekt WHERE fec >= vFec - INTERVAL 1 DAY - AND (( - vKlo = vDefaultKlo + AND ( + (vKlo = vDefaultKlo AND (klo = vKlo OR klo IS NULL OR klo = 0) - AND agj IN (vShortAgj, vLongAgj, vXtraLongAgj)) - OR (klo = vKlo + AND agj IN (vShortAgj, vLongAgj, vXtraLongAgj) + ) OR ( + klo = vKlo AND auction = vAuction - AND agj = vShortAgj) + AND agj = vShortAgj + ) ) - ORDER BY agj DESC, fec DESC - LIMIT 1; + ORDER BY agj DESC, fec DESC + LIMIT 1; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; @@ -91,9 +90,11 @@ BEGIN IF NOT vIsFound THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e - WHERE e.batchNumber - = LEFT(vBarcode,vUsefulAuctionLeftSegmentLength) + FROM ektRecent e + WHERE e.batchNumber = LEFT( + vBarcode, + vUsefulAuctionLeftSegmentLength + ) AND e.batchNumber > 0; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; @@ -103,7 +104,7 @@ BEGIN IF NOT vIsFound THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e + FROM ektRecent e WHERE e.putOrderFk = vBarcode; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; @@ -113,18 +114,28 @@ BEGIN IF NOT vIsFound THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e - WHERE e.deliveryNumber - = MID(vBarcode, 4, 13) + FROM ektRecent e + WHERE e.deliveryNumber = MID(vBarcode, 4, 13) AND e.deliveryNumber > 0; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; END IF; + + -- Solo campo agj + IF NOT vIsFound THEN + INSERT INTO tmp.ekt + SELECT id + FROM ektRecent + WHERE agj = vShortAgj; + + SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; + END IF; + END CASE; IF vIsFound THEN UPDATE ekt e - JOIN tmp.ekt t ON t.ektFk = e.id + JOIN tmp.ekt t ON t.ektFk = e.id SET e.scanned = TRUE; END IF; END$$ diff --git a/db/routines/floranet/procedures/catalogue_get.sql b/db/routines/floranet/procedures/catalogue_get.sql index 32624f383..7ce32cfac 100644 --- a/db/routines/floranet/procedures/catalogue_get.sql +++ b/db/routines/floranet/procedures/catalogue_get.sql @@ -40,19 +40,28 @@ proc:BEGIN postalCode, `type`, image, - description + description, + addressFk ) - SELECT i.name, - i.`size`, - i.id, + SELECT CONCAT(i.name, ' by ',a.nickname), + r.price + apc.deliveryCost, + r.itemFk, vLanded, vPostalCode, it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), - i.description + i.description, + apc.addressFk FROM vn.item i + JOIN (SELECT itemFk, SUM(quantity * cost) price + FROM recipe + GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.code IN ('FNR','FNP'); + JOIN addressPostCode apc + ON apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + JOIN vn.address a ON a.id = apc.addressFk; SELECT * FROM catalogue diff --git a/db/routines/floranet/procedures/contact_request.sql b/db/routines/floranet/procedures/contact_request.sql index 2ca25b87d..2132a86fc 100644 --- a/db/routines/floranet/procedures/contact_request.sql +++ b/db/routines/floranet/procedures/contact_request.sql @@ -13,8 +13,17 @@ BEGIN /** * Set actions for contact request * - * @param vPostalCode Delivery address postal code + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message */ - + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/deliveryDate_get.sql b/db/routines/floranet/procedures/deliveryDate_get.sql index 75e9d6257..a235e8c31 100644 --- a/db/routines/floranet/procedures/deliveryDate_get.sql +++ b/db/routines/floranet/procedures/deliveryDate_get.sql @@ -21,7 +21,7 @@ BEGIN apc.dayOfWeek - vCurrentDayOfWeek, 7 - apc.dayOfWeek ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance - 12 HOUR minDeliveryTime + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime FROM addressPostCode apc WHERE apc.postCode = vPostalCode HAVING nextDay > minDeliveryTime) sub; diff --git a/db/routines/floranet/procedures/order_confirm.sql b/db/routines/floranet/procedures/order_confirm.sql index b6aec033d..3b9413da9 100644 --- a/db/routines/floranet/procedures/order_confirm.sql +++ b/db/routines/floranet/procedures/order_confirm.sql @@ -1,25 +1,167 @@ -DROP PROCEDURE IF EXISTS floranet.order_confirm; - DELIMITER $$ $$ -CREATE DEFINER=`root`@`localhost`PROCEDURE floranet.order_confirm(vCatalogueFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost`PROCEDURE floranet.order_confirm(vCatalogueFk INT) READS SQL DATA -BEGIN -/** Update order.isPaid field. +proc:BEGIN +/** Update order.isPaid field, and makes the ticket * * @param vCatalogueFk floranet.catalogue.id * * @returns floranet.order.isPaid */ + DECLARE vNewTicketFk INT; + DECLARE vCustomerEmail VARCHAR(255); + DECLARE vFloranetEmail VARCHAR(255); + DECLARE vSubjectEmail VARCHAR(100); + DECLARE vBodyEmail TEXT; + DECLARE vZoneFk INT; + + DECLARE exit handler FOR SQLEXCEPTION + BEGIN + ROLLBACK; + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')) AS `SQLEXCEPTION`; + + CALL vn.mail_insert( + 'floranet@verdnatura.es,pako@verdnatura.es', + 'noreply@verdnatura.es', + 'Floranet.order_confirm failure', + CONCAT('CatalogueFk: ', vCatalogueFk, '\n','ERROR ', IFNULL(@errno, 0), ': ', ifnull(@text, 'texto')) + ); + END; + + IF (SELECT isPaid FROM `order` WHERE catalogueFk = vCatalogueFk) THEN + SELECT CONCAT('CatalogueFk: ', vCatalogueFk, ' Esta orden ya está confirmada') AS `ERROR`; + LEAVE proc; + END IF; + + START TRANSACTION; + UPDATE `order` SET isPaid = TRUE, payed = NOW() WHERE catalogueFk = vCatalogueFk; - SELECT isPaid + SELECT zoneFk + INTO vZoneFk + FROM ( + SELECT zoneFk, COUNT(*) totalCount + FROM vn.ticket t + JOIN catalogue c ON c.id = vCatalogueFk + WHERE t.shipped > util.VN_CURDATE() - INTERVAL 1 YEAR + AND t.addressFk = c.addressFk + GROUP BY zoneFk + ORDER BY totalCount DESC + LIMIT 10000000000000000000 + ) sub + LIMIT 1; + + INSERT INTO vn.ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk + ) + SELECT a.clientFk, + c.dated - INTERVAL 1 DAY, + c.addressFk, + a.agencyModeFk, + a.nickname, + ag.warehouseFk, + NULL, + co.id, + c.dated, + vZoneFk + FROM vn.address a + JOIN vn.agencyMode am ON am.id = a.agencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + JOIN catalogue c ON c.addressFk = a.id + JOIN vn.company co ON co.code = 'VNL' + WHERE c.id = vCatalogueFk; + + SET vNewTicketFk = LAST_INSERT_ID(); + + INSERT INTO vn.sale( + ticketFk, + itemFk, + concept, + price, + quantity) + SELECT + vNewTicketFk, + c.itemFk, + CONCAT('Entrega: ',c.name), + - c.price, + 1 + FROM catalogue c + JOIN addressPostCode apc + ON apc.addressFk = c.addressFk + AND apc.dayOfWeek = dayOfWeek(c.dated) + WHERE c.id = vCatalogueFk; + + INSERT INTO vn.sale( + ticketFk, + itemFk, + concept, + price, + quantity) + SELECT + vNewTicketFk, + r.elementFk, + i.longName, + r.cost, + r.quantity + FROM catalogue c + JOIN recipe r ON r.itemFk = c.itemFk + JOIN vn.item i ON i.id = r.elementFk + WHERE c.id = vCatalogueFk; + + SELECT cl.email, + cf.email, + CONCAT('Nuevo pedido FLORANET para entrega el ',c.dated), + CONCAT_WS('\n', + CONCAT('Producto: ', c.name), + CONCAT('Fecha de entrega: ',c.dated), + CONCAT('Destinatario: ', o.deliveryName), + CONCAT('Dirección: ', o.address), + CONCAT('CP: ', c.postalCode), + CONCAT('Foto: ', c.image), + CONCAT('Mensaje: ', IFNULL(o.message,"Ninguno.")), + CONCAT('Teléfono: ',IFNULL(o.deliveryPhone,"--")), + CONCAT('Observaciones: ', IFNULL(o.observations,"No hay.")) + ) + INTO vCustomerEmail, + vFloranetEmail, + vSubjectEmail, + vBodyEmail + FROM vn.client cl + JOIN vn.address a ON a.clientFk = cl.id + JOIN catalogue c ON c.addressFk = a.id + JOIN `order` o ON o.catalogueFk = c.id + JOIN config cf + WHERE c.id = vCatalogueFk; + + CALL vn.mail_insert( + vCustomerEmail, + vFloranetEmail, + vSubjectEmail, + vBodyEmail); + + SELECT isPaid, vNewTicketFk FROM `order` WHERE catalogueFk = vCatalogueFk; + + COMMIT; + END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/order_put.sql b/db/routines/floranet/procedures/order_put.sql index 979588f8f..c5eb71472 100644 --- a/db/routines/floranet/procedures/order_put.sql +++ b/db/routines/floranet/procedures/order_put.sql @@ -7,7 +7,7 @@ BEGIN * * @param vJsonData The order data in json format */ - INSERT INTO `order` + REPLACE `order` SET catalogueFk = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.products[0].id')), customerName = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.customerName')), email = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.email')), @@ -15,7 +15,8 @@ BEGIN message= JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.message')), deliveryName = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryName')), address = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.address')), - deliveryPhone = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryPhone')); + deliveryPhone = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryPhone')), + observations = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.observations')); SELECT LAST_INSERT_ID() orderFk; END$$ diff --git a/db/routines/floranet/procedures/sliders_get.sql b/db/routines/floranet/procedures/sliders_get.sql index 0e4aa297a..bafda4732 100644 --- a/db/routines/floranet/procedures/sliders_get.sql +++ b/db/routines/floranet/procedures/sliders_get.sql @@ -9,12 +9,11 @@ BEGIN * Returns list of url for sliders. */ SELECT - CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url, - i.longName - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.code IN ('FNR','FNP') - LIMIT 3; - + CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url, + i.longName + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + WHERE it.code IN ('FNR','FNP') + LIMIT 3; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/hedera/procedures/item_getVisible.sql b/db/routines/hedera/procedures/item_getVisible.sql index 8e25eaab3..2f4ef32ab 100644 --- a/db/routines/hedera/procedures/item_getVisible.sql +++ b/db/routines/hedera/procedures/item_getVisible.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`item_getVisible vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -14,7 +14,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn.getInventoryDate(); @@ -23,13 +23,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -74,9 +74,10 @@ BEGIN FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() AND t.warehouseFk = vWarehouse - AND s.alertLevel = 3 + AND s.alertLevel = al.id ) t GROUP BY itemFk HAVING quantity > 0; @@ -108,7 +109,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packagingFk diff --git a/db/routines/hedera/procedures/order_confirmWithUser.sql b/db/routines/hedera/procedures/order_confirmWithUser.sql index 0aeaaf65b..9c932aaa1 100644 --- a/db/routines/hedera/procedures/order_confirmWithUser.sql +++ b/db/routines/hedera/procedures/order_confirmWithUser.sql @@ -62,7 +62,7 @@ BEGIN END; -- Carga los datos del pedido - SELECT o.date_send, o.address_id, o.note, a.clientFk, + SELECT o.date_send, o.address_id, o.note, a.clientFk, o.company_id, o.agency_id, c.isTaxDataChecked INTO vDelivery, vAddress, vNotes, vClientId, vCompanyId, vAgencyModeId, vIsTaxDataChecked @@ -121,6 +121,7 @@ BEGIN ) SELECT t.id INTO vTicket FROM vn.ticket t + JOIN vn.alertLevel al ON al.code = 'FREE' LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id JOIN hedera.`order` o @@ -131,7 +132,7 @@ BEGIN WHERE o.id = vSelf AND t.refFk IS NULL AND tp.ticketFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 + AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id) LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado diff --git a/db/routines/hedera/procedures/tpvTransaction_confirm.sql b/db/routines/hedera/procedures/tpvTransaction_confirm.sql index e4a8c932f..60a6d8452 100644 --- a/db/routines/hedera/procedures/tpvTransaction_confirm.sql +++ b/db/routines/hedera/procedures/tpvTransaction_confirm.sql @@ -81,7 +81,7 @@ BEGIN -- Código redundante - DO vn.till_new( + CALL vn.till_new( vCustomer ,vBank ,vAmount / 100 diff --git a/db/routines/srt/functions/expedition_getDayMinute.sql b/db/routines/srt/functions/expedition_getDayMinute.sql index 9331f77e5..01ff534f5 100644 --- a/db/routines/srt/functions/expedition_getDayMinute.sql +++ b/db/routines/srt/functions/expedition_getDayMinute.sql @@ -22,7 +22,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk - LEFT JOIN vn.roadmapStop rs ON rm.expeditionTruckFk = rs.id + LEFT JOIN vn.roadmapStop rs ON rm.roadmapStopFk = rs.id WHERE e.id = vExpeditionFk; RETURN vDayMinute; diff --git a/db/routines/srt/views/bufferDayMinute.sql b/db/routines/srt/views/bufferDayMinute.sql index 41db2bcf7..d2108e513 100644 --- a/db/routines/srt/views/bufferDayMinute.sql +++ b/db/routines/srt/views/bufferDayMinute.sql @@ -34,7 +34,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`) ) LEFT JOIN `vn`.`zone` `z` ON(`z`.`id` = `t`.`zoneFk`) ) diff --git a/db/routines/srt/views/bufferStock.sql b/db/routines/srt/views/bufferStock.sql index 7494cf0a9..ca04d3c01 100644 --- a/db/routines/srt/views/bufferStock.sql +++ b/db/routines/srt/views/bufferStock.sql @@ -45,7 +45,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`) ) JOIN `srt`.`config` `c` ) diff --git a/db/routines/srt/views/upperStickers.sql b/db/routines/srt/views/upperStickers.sql index a230408d9..1cd72c12b 100644 --- a/db/routines/srt/views/upperStickers.sql +++ b/db/routines/srt/views/upperStickers.sql @@ -32,7 +32,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`) ) JOIN `dipole`.`expedition_PrintOut` `epo` ON(`epo`.`expeditionFk` = `e`.`id`) ) diff --git a/db/routines/stock/procedures/log_refreshSale.sql b/db/routines/stock/procedures/log_refreshSale.sql index 983616dca..3054f8ecb 100644 --- a/db/routines/stock/procedures/log_refreshSale.sql +++ b/db/routines/stock/procedures/log_refreshSale.sql @@ -16,12 +16,13 @@ BEGIN m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked + m.isPicked OR s.alertLevel > al.id isPicked FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.alertLevel al ON al.code = 'ON_PREPARATION' WHERE ( vTableId IS NULL OR (vTableName = 'ticket' AND t.id = vTableId) diff --git a/db/routines/util/functions/midnight.sql b/db/routines/util/functions/midnight.sql index c80abdbb0..b37415682 100644 --- a/db/routines/util/functions/midnight.sql +++ b/db/routines/util/functions/midnight.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`midnight`() RETURNS datetime - NOT DETERMINISTIC + DETERMINISTIC READS SQL DATA BEGIN diff --git a/db/routines/util/procedures/tx_commit.sql b/db/routines/util/procedures/tx_commit.sql index fdf2f3ddb..35f96df8d 100644 --- a/db/routines/util/procedures/tx_commit.sql +++ b/db/routines/util/procedures/tx_commit.sql @@ -1,12 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_commit`(isTx BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_commit`(vIsTx BOOL) BEGIN /** * Confirma los cambios asociados a una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF isTx THEN + IF vIsTx THEN COMMIT; END IF; END$$ diff --git a/db/routines/util/procedures/tx_rollback.sql b/db/routines/util/procedures/tx_rollback.sql index 96571af2c..4b00f9ec1 100644 --- a/db/routines/util/procedures/tx_rollback.sql +++ b/db/routines/util/procedures/tx_rollback.sql @@ -1,12 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_rollback`(isTx BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_rollback`(vIsTx BOOL) BEGIN /** * Deshace los cambios asociados a una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF isTx THEN + IF vIsTx THEN ROLLBACK; END IF; END$$ diff --git a/db/routines/util/procedures/tx_start.sql b/db/routines/util/procedures/tx_start.sql index 9d9f16bb7..41f8c94ee 100644 --- a/db/routines/util/procedures/tx_start.sql +++ b/db/routines/util/procedures/tx_start.sql @@ -1,12 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_start`(isTx BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_start`(vIsTx BOOL) BEGIN /** * Inicia una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF isTx THEN + IF vIsTx THEN START TRANSACTION; END IF; END$$ diff --git a/db/routines/vn/events/client_userDisable.sql b/db/routines/vn/events/client_userDisable.sql new file mode 100644 index 000000000..b3354f8fd --- /dev/null +++ b/db/routines/vn/events/client_userDisable.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`client_userDisable` + ON SCHEDULE EVERY 1 MONTH + STARTS '2023-06-01 00:00:00.000' + ON COMPLETION PRESERVE + ENABLE +DO CALL client_userDisable()$$ +DELIMITER ; diff --git a/db/routines/vn/events/clientsDisable.sql b/db/routines/vn/events/clientsDisable.sql deleted file mode 100644 index 35e6554a2..000000000 --- a/db/routines/vn/events/clientsDisable.sql +++ /dev/null @@ -1,25 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`clientsDisable` - ON SCHEDULE EVERY 1 MONTH - STARTS '2023-06-01 00:00:00.000' - ON COMPLETION PRESERVE - ENABLE -DO BEGIN - UPDATE account.user u - JOIN client c ON c.id = u.id - LEFT JOIN account.account a ON a.id = u.id - SET u.active = FALSE - WHERE c.typeFk = 'normal' - AND a.id IS NULL - AND u.active - AND c.created < util.VN_CURDATE() - INTERVAL 12 MONTH - AND u.id NOT IN ( - SELECT DISTINCT c.id - FROM client c - LEFT JOIN ticket t ON t.clientFk = c.id - WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL 12 MONTH - OR shipped > util.VN_CURDATE() - INTERVAL 12 MONTH - ); -END$$ -DELIMITER ; diff --git a/db/routines/vn/functions/client_getFromPhone.sql b/db/routines/vn/functions/client_getFromPhone.sql index c6ded691b..5e4daa532 100644 --- a/db/routines/vn/functions/client_getFromPhone.sql +++ b/db/routines/vn/functions/client_getFromPhone.sql @@ -11,10 +11,7 @@ BEGIN */ DECLARE vClient INT DEFAULT NULL; - -- SET vPhone = vPhone COLLATE 'utf8_unicode_ci'; - - DROP TEMPORARY TABLE IF EXISTS tClient; - CREATE TEMPORARY TABLE tClient + CREATE OR REPLACE TEMPORARY TABLE tClient ENGINE = MEMORY SELECT id clientFk FROM `client` @@ -27,13 +24,14 @@ BEGIN OR mobile = vPhone UNION SELECT clientFk - FROM vn.clientContact + FROM clientContact WHERE phone = vPhone; SELECT t.clientFk INTO vClient FROM tClient t JOIN `client` c ON c.id = t.clientFk WHERE c.isActive + AND c.salesPersonFk LIMIT 1; DROP TEMPORARY TABLE tClient; diff --git a/db/routines/vn/functions/ticket_isTooLittle.sql b/db/routines/vn/functions/ticket_isTooLittle.sql index 2ce24f0fa..bcbf09035 100644 --- a/db/routines/vn/functions/ticket_isTooLittle.sql +++ b/db/routines/vn/functions/ticket_isTooLittle.sql @@ -14,7 +14,7 @@ BEGIN DECLARE vIsTooLittle TINYINT(1); SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume - OR IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle + AND IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle FROM ticket t LEFT JOIN saleVolume sv ON sv.ticketFk = t.id JOIN volumeConfig vc diff --git a/db/routines/vn/functions/till_new.sql b/db/routines/vn/functions/till_new.sql index 24f4f2b79..b93072596 100644 --- a/db/routines/vn/functions/till_new.sql +++ b/db/routines/vn/functions/till_new.sql @@ -1,79 +1,73 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`till_new`(vClient INT - ,vBank INT - ,vAmount DOUBLE - ,vConcept VARCHAR(25) - ,vDated DATE - ,vSerie CHAR(1) - ,vBatch TINYINT - ,vNumber INT - ,vCompany SMALLINT - ,vWorker INT +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`till_new`( + vClient INT, + vBank INT, + vAmount DOUBLE, + vConcept VARCHAR(25), + vDated DATE, + vSerie CHAR(1), + vBatch TINYINT, + vNumber INT, + vCompany SMALLINT, + vWorker INT ) - RETURNS int(11) - DETERMINISTIC BEGIN DECLARE vAccount VARCHAR(12); DECLARE vSubaccount VARCHAR(12); DECLARE vAsiento INT DEFAULT NULL; -- Inserta el registro en cajas - INSERT INTO till SET - workerFk = vWorker - ,bankFk = vBank - ,`in` = vAmount - ,concept = vConcept - ,dated = vDated - ,serie = vSerie - ,isAccountable = vBatch - ,`number` = vNumber - ,companyFk = vCompany; + workerFk = vWorker, + bankFk = vBank, + `in` = vAmount, + concept = vConcept, + dated = vDated, + serie = vSerie, + isAccountable = vBatch, + `number` = vNumber, + companyFk = vCompany; -- Inserta los asientos contables - SELECT account INTO vAccount FROM accounting WHERE id = vBank; SELECT accountingAccount INTO vSubaccount FROM `client` WHERE id = vClient; - SET vAsiento = xdiario_new - ( - vAsiento - ,vDated - ,vAccount - ,vSubaccount - ,vConcept - ,vAmount - ,0 - ,0 - ,NULL -- Serie - ,NULL -- Factura - ,NULL -- IVA - ,NULL -- Recargo - ,FALSE -- Auxiliar - ,vCompany - ); - DO xdiario_new - ( - vAsiento - ,vDated - ,vSubaccount - ,vAccount - ,vConcept - ,0 - ,vAmount - ,0 - ,NULL -- Serie - ,NULL -- Factura - ,NULL -- IVA - ,NULL -- Recargo - ,FALSE -- Auxiliar - ,vCompany - ); + CALL xdiario_new( + vAsiento, + vDated, + vAccount, + vSubaccount, + vConcept, + vAmount, + 0, + 0, + NULL, -- Serie + NULL, -- Factura + NULL, -- IVA + NULL, -- Recargo + FALSE, -- Auxiliar + vCompany, + vAsiento); - RETURN NULL; + CALL xdiario_new( + vAsiento, + vDated, + vSubaccount, + vAccount, + vConcept, + 0, + vAmount, + 0, + NULL, -- Serie + NULL, -- Factura + NULL, -- IVA + NULL, -- Recargo + FALSE, -- Auxiliar + vCompany, + vAsiento); END$$ DELIMITER ; diff --git a/db/routines/vn/functions/xdiario_new.sql b/db/routines/vn/functions/xdiario_new.sql deleted file mode 100644 index 4f4b3f3fd..000000000 --- a/db/routines/vn/functions/xdiario_new.sql +++ /dev/null @@ -1,45 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`xdiario_new`( - vBookNumber INT, - vDated DATE, - vSubaccount VARCHAR(12), - vAccount VARCHAR(12), - vConcept VARCHAR(25), - vDebit DOUBLE, - vCredit DOUBLE, - vEuro DOUBLE, - vSerie CHAR(1), - vInvoice VARCHAR(8), - vVat DOUBLE, - vRe DOUBLE, - vAux TINYINT, - vCompanyFk INT -) - RETURNS int(11) - NOT DETERMINISTIC - NO SQL -BEGIN - IF vBookNumber IS NULL THEN - CALL ledger_next(YEAR(vDated), vBookNumber); - END IF; - - INSERT INTO XDiario - SET ASIEN = vBookNumber, - FECHA = vDated, - SUBCTA = vSubaccount, - CONTRA = vAccount, - CONCEPTO = vConcept, - EURODEBE = vDebit, - EUROHABER = vCredit, - BASEEURO = vEuro, - SERIE = vSerie, - FACTURA = vInvoice, - IVA = vVat, - RECEQUIV = vRe, - AUXILIAR = IF(vAux = FALSE, NULL, '*'), - MONEDAUSO = 2, - empresa_id = vCompanyFk; - - RETURN vBookNumber; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/buy_afterUpsert.sql b/db/routines/vn/procedures/buy_afterUpsert.sql index 17e84177c..76f60d1e5 100644 --- a/db/routines/vn/procedures/buy_afterUpsert.sql +++ b/db/routines/vn/procedures/buy_afterUpsert.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`( + vSelf INT +) BEGIN /** * Triggered actions when a buy is updated or inserted. @@ -16,7 +18,7 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - + SELECT b.entryFk, b.itemFk, i.packingOut, @@ -47,8 +49,11 @@ BEGIN WHERE e.id = vEntryFk; IF vIsMerchandise THEN + IF vWarehouse IS NULL THEN + CALL util.throw('The entry does not have travel'); + END IF; - REPLACE itemCost SET + REPLACE itemCost SET itemFk = vItemFk, warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), @@ -74,7 +79,7 @@ BEGIN WHERE b.id = vSelf; END IF; - CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck + CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck SELECT vSelf id; CALL buy_checkItem(); END$$ diff --git a/db/routines/vn/procedures/buy_clone.sql b/db/routines/vn/procedures/buy_clone.sql new file mode 100644 index 000000000..7b77204c9 --- /dev/null +++ b/db/routines/vn/procedures/buy_clone.sql @@ -0,0 +1,57 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_clone`(vEntryFk INT) +BEGIN +/** + * Clone buys to an entry + * + * @param vEntryFk The entry id + * @table tmp.buy(id) + */ + INSERT INTO buy( + entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk) + SELECT vEntryFk, + b.itemFk, + b.quantity, + b.buyingValue, + b.freightValue, + b.isIgnored, + b.stickers, + b.packagingFk, + b.packing, + b.`grouping`, + b.groupingMode, + b.comissionValue, + b.packageValue, + b.price1, + b.price2, + b.price3, + b.minPrice, + b.isChecked, + b.location, + b.weight, + b.itemOriginalFk + FROM tmp.buy tb + JOIN vn.buy b ON b.id = tb.id; + +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/buy_recalcPricesByBuy.sql b/db/routines/vn/procedures/buy_recalcPricesByBuy.sql index 4fff4d313..b699e42d7 100644 --- a/db/routines/vn/procedures/buy_recalcPricesByBuy.sql +++ b/db/routines/vn/procedures/buy_recalcPricesByBuy.sql @@ -10,7 +10,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; - CREATE TEMPORARY TABLE tmp.buyRecalc + CREATE TEMPORARY TABLE tmp.buyRecalc SELECT vBuyFk id; CALL buy_recalcPrices(); diff --git a/db/routines/vn/procedures/client_userDisable.sql b/db/routines/vn/procedures/client_userDisable.sql new file mode 100644 index 000000000..f2ba65c1c --- /dev/null +++ b/db/routines/vn/procedures/client_userDisable.sql @@ -0,0 +1,33 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_userDisable`() +BEGIN +/** +* Desactiva los clientes inactivos en los últimos X meses. +*/ + DECLARE vMonths INT; + + SELECT monthsToDisableUser INTO vMonths + FROM clientConfig; + + IF vMonths IS NULL THEN + CALL util.throw('Config parameter not set'); + END IF; + + UPDATE account.user u + JOIN client c ON c.id = u.id + LEFT JOIN account.account a ON a.id = u.id + SET u.active = FALSE + WHERE c.typeFk = 'normal' + AND a.id IS NULL + AND u.active + AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH + AND u.id NOT IN ( + SELECT DISTINCT c.id + FROM client c + LEFT JOIN ticket t ON t.clientFk = c.id + WHERE c.salesPersonFk IS NOT NULL + OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH + OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH + ); +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index c2b6e538e..fc9f9a711 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -13,27 +13,12 @@ BEGIN * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vWarehouseFk INT; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - END IF; - - RESIGNAL; - END; -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, - collection_assign_lockname - INTO vHasTooMuchCollections, - vLockName + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 + INTO vHasTooMuchCollections FROM productionConfig pc LEFT JOIN tCollection ON TRUE; @@ -43,21 +28,6 @@ BEGIN CALL util.throw('Hay colecciones pendientes'); END IF; - SELECT warehouseFk, itemPackingTypeFk - INTO vWarehouseFk, vItemPackingTypeFk - FROM operator - WHERE workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); - END IF; - -- Se eliminan las colecciones sin asignar que estan obsoletas INSERT INTO ticketTracking(stateFk, ticketFk) SELECT s.id, tc.ticketFk @@ -65,7 +35,7 @@ BEGIN JOIN ticketCollection tc ON tc.collectionFk = c.id JOIN `state` s ON s.code = 'PRINTED_AUTO' JOIN productionConfig pc - WHERE c.workerFk IS NULL + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* @@ -79,8 +49,7 @@ BEGIN VALUES(vUserFk); -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) - INTO vCollectionFk + SELECT MIN(c.id) INTO vCollectionFk FROM `collection` c JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) @@ -106,7 +75,5 @@ BEGIN UPDATE `collection` SET workerFk = vUserFk WHERE id = vCollectionFk; - - DO RELEASE_LOCK(vLockName); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index 8a1eff4a1..fa947ddef 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -49,6 +49,10 @@ BEGIN BEGIN IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); + CALL util.debugAdd(JSON_OBJECT( + 'type', 'releaseLock', + 'userFk', vUserFk + ), vLockName); -- Tmp END IF; RESIGNAL; diff --git a/db/routines/vn/procedures/conveyorExpedition_Add.sql b/db/routines/vn/procedures/conveyorExpedition_Add.sql index daaf33f2f..94cbc88e2 100644 --- a/db/routines/vn/procedures/conveyorExpedition_Add.sql +++ b/db/routines/vn/procedures/conveyorExpedition_Add.sql @@ -34,7 +34,7 @@ BEGIN LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.agency a ON a.id = am.agencyFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 981f3026d..8b4df6a73 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -6,12 +6,12 @@ BEGIN * * @param vDuaFk Id del dua a recalcular */ - DECLARE done BOOL DEFAULT FALSE; + DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; - DECLARE vASIEN BIGINT DEFAULT 0; - DECLARE vCounter INT DEFAULT 0; + DECLARE vBookEntry INT; + DECLARE vFiscalYear INT; - DECLARE rs CURSOR FOR + DECLARE vInvoicesIn CURSOR FOR SELECT DISTINCT e.invoiceInFk FROM entry e JOIN duaEntry de ON de.entryFk = e.id @@ -20,9 +20,7 @@ BEGIN AND de.customsValue AND ii.isBooked = FALSE; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; UPDATE invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id @@ -36,38 +34,36 @@ BEGIN e.isConfirmed = TRUE WHERE d.id = vDuaFk; - SELECT IFNULL(ASIEN,0) INTO vASIEN - FROM dua - WHERE id = vDuaFk; + SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - FETCH rs INTO vInvoiceFk; + IF vBookEntry IS NULL THEN + SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear + FROM invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + WHERE d.id = vDuaFk + LIMIT 1; + CALL ledger_nextTx(vFiscalYear, vBookEntry); + END IF; - WHILE NOT done DO + OPEN vInvoicesIn; - CALL invoiceIn_booking(vInvoiceFk); - - IF vCounter > 0 OR vASIEN > 0 THEN - - UPDATE XDiario x - JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN - SET x.ASIEN = vASIEN; - - ELSE - - SELECT lastBookEntry INTO vASIEN FROM ledgerConfig; +l: LOOP + SET vDone = FALSE; + FETCH vInvoicesIn INTO vInvoiceFk; + IF vDone THEN + LEAVE l; END IF; - SET vCounter = vCounter + 1; + CALL invoiceIn_booking(vInvoiceFk, vBookEntry); + END LOOP; - FETCH rs INTO vInvoiceFk; - - END WHILE; - - CLOSE rs; + CLOSE vInvoicesIn; UPDATE dua - SET ASIEN = vASIEN + SET ASIEN = vBookEntry WHERE id = vDuaFk; UPDATE invoiceIn ii diff --git a/db/routines/vn/procedures/duaTaxBooking.sql b/db/routines/vn/procedures/duaTaxBooking.sql index 5d4a98933..a50a10ca4 100644 --- a/db/routines/vn/procedures/duaTaxBooking.sql +++ b/db/routines/vn/procedures/duaTaxBooking.sql @@ -12,7 +12,7 @@ BEGIN WHERE id = vDuaFk; IF vBookNumber IS NULL OR NOT vBookNumber THEN - CALL ledger_next(YEAR(vBookDated), vBookNumber); + CALL ledger_nextTx(YEAR(vBookDated), vBookNumber); END IF; -- Apunte de la aduana diff --git a/db/routines/vn/procedures/entry_checkBooked.sql b/db/routines/vn/procedures/entry_checkBooked.sql deleted file mode 100644 index 7ee1fee22..000000000 --- a/db/routines/vn/procedures/entry_checkBooked.sql +++ /dev/null @@ -1,22 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkBooked`( - vSelf INT -) -BEGIN -/** - * Comprueba si una entrada está contabilizada, - * y si lo está retorna un throw. - * - * @param vSelf Id de entrada - */ - DECLARE vIsBooked BOOL; - - SELECT isBooked INTO vIsBooked - FROM `entry` - WHERE id = vSelf; - - IF vIsBooked AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is already booked'); - END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/entry_cloneHeader.sql b/db/routines/vn/procedures/entry_cloneHeader.sql index 6a6df9194..7f9426663 100644 --- a/db/routines/vn/procedures/entry_cloneHeader.sql +++ b/db/routines/vn/procedures/entry_cloneHeader.sql @@ -9,8 +9,8 @@ BEGIN * Clones an entry header. * * @param vSelf The entry id + * @param OUT vNewEntryFk The new entry id * @param vTravelFk Travel for the new entry or %NULL to use the source entry travel - * @param vNewEntryFk The new entry id */ INSERT INTO entry( travelFk, diff --git a/db/routines/vn/procedures/entry_copyBuys.sql b/db/routines/vn/procedures/entry_copyBuys.sql index a00fbc846..9bf4a55e4 100644 --- a/db/routines/vn/procedures/entry_copyBuys.sql +++ b/db/routines/vn/procedures/entry_copyBuys.sql @@ -1,59 +1,18 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_copyBuys`(vSelf INT, vCopyTo INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_copyBuys`(vSelf INT, vDestinationEntryFk INT) BEGIN /** - * Copies an entry buys to another buy. + * Copies all buys from an entry to an entry. * * @param vSelf The entry id - * @param vCopyTo The destination entry id + * @param vDestinationEntryFk The destination entry id */ - INSERT INTO buy( - entryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - containerFk, - comissionValue, - packageValue, - packagingFk, - price1, - price2, - price3, - minPrice, - isChecked, - location, - weight, - itemOriginalFk - ) - SELECT vCopyTo, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - containerFk, - comissionValue, - packageValue, - packagingFk, - price1, - price2, - price3, - minPrice, - isChecked, - location, - weight, - itemOriginalFk + CREATE OR REPLACE TEMPORARY TABLE tmp.buy + SELECT id FROM buy WHERE entryFk = vSelf; + + CALL buy_clone(vDestinationEntryFk); + DROP TEMPORARY TABLE tmp.buy; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/entry_fixMisfit.sql b/db/routines/vn/procedures/entry_fixMisfit.sql index 3e57d362e..986a0ae9e 100644 --- a/db/routines/vn/procedures/entry_fixMisfit.sql +++ b/db/routines/vn/procedures/entry_fixMisfit.sql @@ -26,7 +26,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -46,7 +45,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql new file mode 100644 index 000000000..a05a1fd92 --- /dev/null +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -0,0 +1,24 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_isEditable`( + vSelf INT +) +BEGIN +/** + * Comprueba si una entrada se puede actualizar + * si no se puede retorna un throw. + * + * @param vSelf Id de entrada + */ + DECLARE vIsEditable BOOL; + + SELECT e.isBooked INTO vIsEditable + FROM `entry` e + JOIN entryType et ON et.code = e.typeFk + WHERE NOT et.isInformal + AND e.id = vSelf; + + IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN + CALL util.throw('Entry is not editable'); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/entry_moveNotPrinted.sql b/db/routines/vn/procedures/entry_moveNotPrinted.sql index 526ae9d43..3a12007d1 100644 --- a/db/routines/vn/procedures/entry_moveNotPrinted.sql +++ b/db/routines/vn/procedures/entry_moveNotPrinted.sql @@ -56,7 +56,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, packagingFk, @@ -77,7 +76,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, packagingFk, @@ -114,7 +112,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -133,7 +130,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index b7d9c77b3..2898141ea 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -76,7 +76,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, @@ -103,7 +102,6 @@ BEGIN packing, `grouping`, groupingMode, - containerFk, comissionValue, packageValue, location, diff --git a/db/routines/vn/procedures/entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql index ceed20d78..4ec4f6e58 100644 --- a/db/routines/vn/procedures/entry_updateComission.sql +++ b/db/routines/vn/procedures/entry_updateComission.sql @@ -23,7 +23,8 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() - AND e.currencyFk = vCurrency; + AND e.currencyFk = vCurrency + AND NOT e.isBooked; SET vComission = currency_getCommission(vCurrency); diff --git a/db/routines/vn/procedures/expeditionPallet_build.sql b/db/routines/vn/procedures/expeditionPallet_build.sql index 9fbb60100..bea56eae6 100644 --- a/db/routines/vn/procedures/expeditionPallet_build.sql +++ b/db/routines/vn/procedures/expeditionPallet_build.sql @@ -56,13 +56,13 @@ BEGIN LIMIT 1; IF vPalletFk IS NULL THEN - SELECT expeditionTruckFk + SELECT roadmapStopFk INTO vTruckFk FROM ( - SELECT rm.expeditionTruckFk, count(*) n + SELECT rm.roadmapStopFk, count(*) n FROM vn.routesMonitor rm JOIN tExpedition e ON e.routeFk = rm.routeFk - GROUP BY expeditionTruckFk + GROUP BY roadmapStopFk ORDER BY n DESC LIMIT 1) sub; diff --git a/db/routines/vn/procedures/expeditionTruck_Add.sql b/db/routines/vn/procedures/expeditionTruck_Add.sql deleted file mode 100644 index eabfa452c..000000000 --- a/db/routines/vn/procedures/expeditionTruck_Add.sql +++ /dev/null @@ -1,9 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45)) -BEGIN - - INSERT INTO vn.roadmapStop(eta,description) - VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription); - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/expeditionTruck_List.sql b/db/routines/vn/procedures/expeditionTruck_List.sql deleted file mode 100644 index c358df5e3..000000000 --- a/db/routines/vn/procedures/expeditionTruck_List.sql +++ /dev/null @@ -1,12 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_List`() -BEGIN - - SELECT id truckFk, - eta, - description Destino - FROM roadmapStop - WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - ORDER BY eta; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/expedition_StateGet.sql b/db/routines/vn/procedures/expedition_StateGet.sql index e58ec3afd..c709841eb 100644 --- a/db/routines/vn/procedures/expedition_StateGet.sql +++ b/db/routines/vn/procedures/expedition_StateGet.sql @@ -67,7 +67,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END$$ diff --git a/db/routines/vn/procedures/expedition_getFromRoute.sql b/db/routines/vn/procedures/expedition_getFromRoute.sql index 2b4de5662..2b726fa7d 100644 --- a/db/routines/vn/procedures/expedition_getFromRoute.sql +++ b/db/routines/vn/procedures/expedition_getFromRoute.sql @@ -15,7 +15,8 @@ BEGIN t.addressFk, a.nickname, sub2.itemPackingTypeConcat, - est.code + est.code, + es.isScanned FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = e.ticketFk @@ -33,6 +34,10 @@ BEGIN GROUP BY sub.ticketFk ) sub2 ON sub2.ticketFk = t.id LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk + LEFT JOIN expeditionState es ON es.id = ( + SELECT MAX(id) + FROM expeditionState es + WHERE expeditionFk = e.id) WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE ORDER BY r.created, t.priority DESC; END$$ diff --git a/db/routines/vn/procedures/expedition_getState.sql b/db/routines/vn/procedures/expedition_getState.sql index f3f94a889..61d65f571 100644 --- a/db/routines/vn/procedures/expedition_getState.sql +++ b/db/routines/vn/procedures/expedition_getState.sql @@ -50,7 +50,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END$$ diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index 4b015750f..ef124bb46 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -1,7 +1,17 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceIn_booking`(vSelf INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceIn_booking`( + vSelf INT, + vBookNumber INT +) BEGIN - DECLARE vBookNumber INT; +/** + * Genera la contabilidad para una factura y la marca como contabilizada + * Cuadra el asiento generado en si encuentra problemas derivados + * de los calculos con decimales + * + * @param vSelf Id invoiceIn + * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo + */ DECLARE vFiscalYear INT; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn @@ -58,7 +68,10 @@ BEGIN WHERE ii.id = vSelf; SELECT YEAR(bookEntried) INTO vFiscalYear FROM tInvoiceIn LIMIT 1; - CALL ledger_next(vFiscalYear, vBookNumber); + + IF vBookNumber IS NULL THEN + CALL ledger_nextTx(vFiscalYear, vBookNumber); + END IF; -- Apunte del proveedor INSERT INTO XDiario( @@ -187,7 +200,7 @@ BEGIN LEFT JOIN ( SELECT e.id FROM tInvoiceIn tii - JOIN expense e ON e.id = tii.expenseFk + JOIN expense e ON e.id = tii.expenseFk WHERE e.isWithheld LIMIT 1 ) eWithheld ON TRUE diff --git a/db/routines/vn/procedures/invoiceOutBooking.sql b/db/routines/vn/procedures/invoiceOutBooking.sql index 913035576..9fc1c92b6 100644 --- a/db/routines/vn/procedures/invoiceOutBooking.sql +++ b/db/routines/vn/procedures/invoiceOutBooking.sql @@ -61,7 +61,7 @@ BEGIN WHERE io.id = vInvoice; SELECT YEAR(FECHA) INTO vFiscalYear FROM rs LIMIT 1; - CALL ledger_next(vFiscalYear, vBookNumber); + CALL ledger_nextTx(vFiscalYear, vBookNumber); -- Linea del cliente INSERT INTO XDiario( ASIEN, diff --git a/db/routines/vn/procedures/invoiceOut_new.sql b/db/routines/vn/procedures/invoiceOut_new.sql index 1b486df86..42c3f99da 100644 --- a/db/routines/vn/procedures/invoiceOut_new.sql +++ b/db/routines/vn/procedures/invoiceOut_new.sql @@ -80,8 +80,8 @@ BEGIN OR t.isDeleted OR c.hasToInvoice = FALSE OR itc.id IS NULL - OR a.id IS NULL - OR (vTaxArea = 'WORLD' + OR a.id IS NULL + OR (vTaxArea = 'WORLD' AND (a.customsAgentFk IS NULL OR a.incotermsFk IS NULL)); SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0 @@ -153,7 +153,9 @@ BEGIN FROM tmp.ticketToInvoice ti LEFT JOIN ticketState ts ON ti.id = ts.ticketFk JOIN state s - WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id); + JOIN alertLevel al ON al.code = 'DELIVERED' + WHERE (ts.alertLevel IS NULL OR ts.alertLevel < al.id) + AND s.`code` = getAlert3State(ti.id); INSERT INTO ticketTracking(stateFk, ticketFk, userFk) SELECT * FROM tmp.updateInter; diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql index bdc13ae9d..86d62cad4 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql @@ -18,11 +18,12 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk JOIN vn.warehouse w ON w.id = sc.warehouseFk - WHERE sc.id = vSectorFk - AND ish.visible > 0 + WHERE ish.visible > 0 AND ish.itemFk = vItemFk GROUP BY ish.id - ORDER BY sh.priority DESC, + ORDER BY + (sc.id = vSectorFk) DESC, + sh.priority DESC, ish.created, p.pickingOrder; END$$ diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql index 7875c4791..aa95d0503 100644 --- a/db/routines/vn/procedures/itemShelvingRadar.sql +++ b/db/routines/vn/procedures/itemShelvingRadar.sql @@ -49,7 +49,7 @@ BEGIN ish.isChecked, sub.isAllChecked FROM itemShelvingStock iss - JOIN itemShelving ish ON ish.shelvingFk = iss.shelvingFk + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN ( SELECT itemFk, IF( diff --git a/db/routines/vn/procedures/itemShelvingTransfer.sql b/db/routines/vn/procedures/itemShelvingTransfer.sql index 326f8108b..ae82bfe9d 100644 --- a/db/routines/vn/procedures/itemShelvingTransfer.sql +++ b/db/routines/vn/procedures/itemShelvingTransfer.sql @@ -17,13 +17,15 @@ BEGIN SELECT itemFk, packing, - created + created, + buyFk FROM itemShelving WHERE id = vItemShelvingFk ) ish2 ON ish2.itemFk = ish.itemFk AND ish2.packing = ish.packing AND date(ish2.created) = date(ish.created) + AND ish2.buyFk = ish.buyFk WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; IF vNewItemShelvingFk THEN diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index d3e0f6a90..9395f5d80 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -2,7 +2,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN - /** * Añade registro o lo actualiza si ya existe. * @@ -15,11 +14,23 @@ BEGIN * @param vWarehouseFk indica el sector * **/ - DECLARE vItemFk INT; + DECLARE vBuyFk INT; + + SELECT id INTO vBuyFk + FROM buy WHERE id = vBarcode; SELECT barcodeToItem(vBarcode) INTO vItemFk; + IF vBuyFk IS NULL THEN + CALL cache.last_buy_refresh(FALSE); + + SELECT buy_id INTO vBuyFk + FROM cache.last_buy + WHERE item_id = vItemFk + AND warehouse_id = vWarehouseFk; + END IF; + IF vPacking IS NULL THEN SET vPacking = itemPacking(vBarcode, vWarehouseFk); @@ -29,31 +40,32 @@ BEGIN IF (SELECT COUNT(*) FROM itemShelving WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk - AND packing = vPacking) = 1 THEN + AND packing = vPacking + AND buyFk = vBuyFk) THEN UPDATE itemShelving - SET visible = visible+vQuantity + SET visible = visible + vQuantity WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; ELSE - CALL cache.last_buy_refresh(FALSE); - INSERT INTO itemShelving( itemFk, - shelvingFk, - visible, - grouping, - packing, - packagingFk) - SELECT vItemFk, - vShelvingFk, - vQuantity, - IFNULL(vGrouping, b.grouping), - IFNULL(vPacking, b.packing), - IFNULL(vPackagingFk, b.packagingFk) - FROM item i - LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - WHERE i.id = vItemFk; + INSERT INTO itemShelving( + itemFk, + shelvingFk, + visible, + grouping, + packing, + packagingFk, + buyFk) + SELECT vItemFk, + vShelvingFk, + vQuantity, + IFNULL(vGrouping, b.grouping), + IFNULL(vPacking, b.packing), + IFNULL(vPackagingFk, b.packagingFk), + id + FROM buy b + WHERE id = vBuyFk; END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelving_getItemDetails.sql b/db/routines/vn/procedures/itemShelving_getItemDetails.sql new file mode 100644 index 000000000..c01bc348c --- /dev/null +++ b/db/routines/vn/procedures/itemShelving_getItemDetails.sql @@ -0,0 +1,55 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_getItemDetails`( + vBarcodeItem INT, + vShelvingFK VARCHAR(10) +) +BEGIN +/** + * Obtiene el precio y visible de un item + * + * @param vBarcodeItem barcode de artículo + * @param vShelvingFK Ubicación actual del artículo + */ + DECLARE vIsItem BOOL; + DECLARE vBuyFk INT; + DECLARE vWarehouseFk INT; + + SELECT COUNT(*) > 0 INTO vIsItem + FROM item + WHERE id = vBarcodeItem; + + IF vIsItem THEN + SELECT warehouseFk INTO vWarehouseFk + FROM operator + WHERE workerFk = account.myUser_getId(); + + CALL buyUltimate(vWarehouseFk, util.VN_CURDATE()); + + SELECT buyFk INTO vBuyFk + FROM tmp.buyUltimate + WHERE itemFk = vBarcodeItem + AND warehouseFk = vWarehouseFk; + + DELETE FROM tmp.buyUltimate; + ELSE + SELECT vBarcodeItem INTO vBuyFk; + END IF; + + WITH visible AS( + SELECT itemFk, + IFNULL(buyingValue, 0) + + IFNULL(freightValue, 0) + + IFNULL(comissionValue, 0) + + IFNULL(packageValue, 0) itemCost + FROM vn.buy b + WHERE b.id = vBuyFk + ) SELECT v.itemFk, + vShelvingFK, + v.itemCost, + SUM(ish.visible) visible + FROM vn.itemShelving ish + JOIN visible v + WHERE ish.shelvingFK = vShelvingFK COLLATE utf8mb3_general_ci + AND ish.itemFk = v.itemFk; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/item_comparative.sql b/db/routines/vn/procedures/item_comparative.sql index e72188363..d429cf009 100644 --- a/db/routines/vn/procedures/item_comparative.sql +++ b/db/routines/vn/procedures/item_comparative.sql @@ -6,7 +6,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_comparative`( vAvailableSince DATE, vBuyerFk INT, vIsFloramondo BOOL, - vCountryFk INT + vCountryFk INT ) proc: BEGIN /** @@ -23,7 +23,6 @@ proc: BEGIN * @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT) * @return tmp.comparative */ - DECLARE vDayRangeStart DATE; DECLARE vDayRangeEnd DATE; DECLARE w1, w2, w3, w4, w5, w6, w7 INT; @@ -59,14 +58,14 @@ proc: BEGIN END IF; SELECT MIN(dated) INTO vDayRangeStart - FROM vn.time + FROM `time` WHERE dated <= vDate GROUP BY period ORDER BY dated desc LIMIT 1 OFFSET vWeekRange; SELECT MAX(dated) INTO vDayRangeEnd - FROM vn.time + FROM `time` WHERE dated >= vDate GROUP BY period ORDER BY dated ASC @@ -83,12 +82,11 @@ proc: BEGIN JOIN itemType t ON t.id = i.typeFk JOIN itemCategory c ON c.id = t.categoryFk LEFT JOIN worker w ON w.id = t.workerFk - WHERE (NOT vHasTypeFilter - OR t.id IN (SELECT itemTypeFk FROM tmp.comparativeFilterType)) - AND (vBuyerFk IS NULL - OR t.workerFk = vBuyerFk) - AND (vIsFloramondo IS NULL - OR i.isFloramondo = vIsFloramondo); + WHERE (NOT vHasTypeFilter OR t.id IN ( + SELECT itemTypeFk FROM tmp.comparativeFilterType + )) + AND (vBuyerFk IS NULL OR t.workerFk = vBuyerFk) + AND (vIsFloramondo IS NULL OR i.isFloramondo = vIsFloramondo); IF vDate < util.VN_CURDATE() THEN ALTER TABLE tmp.itemInventory @@ -115,10 +113,11 @@ proc: BEGIN SET i = i + 1; SELECT t.period INTO vPeriod - FROM vn.`time` t + FROM `time` t WHERE t.dated = vDayRangeStart + INTERVAL (vWeekCount * (i - 1)) DAY; - INSERT IGNORE INTO tTable(cy, ly, zy) VALUES(vPeriod, vPeriod - 100, vPeriod - 200); + INSERT IGNORE INTO tTable(cy, ly, zy) + VALUES(vPeriod, vPeriod - 100, vPeriod - 200); UNTIL i = vWeekCount END REPEAT; SELECT cy, ly, zy INTO w1, y1, z1 FROM tTable LIMIT 1; @@ -130,7 +129,6 @@ proc: BEGIN SELECT cy, ly, zy INTO w7, y7, z7 FROM tTable WHERE cy > w6 LIMIT 1; -- Genera una tabla con los datos del año pasado. - CREATE OR REPLACE TEMPORARY TABLE tLastYear (KEY (lItemFk)) ENGINE = MEMORY @@ -151,15 +149,14 @@ proc: BEGIN SUM(IF(c.timePeriod = y7, c.price, 0)) lprice7 FROM tmp.itemInventory ai JOIN comparative c ON c.itemFk = ai.id - JOIN warehouse w on w.id = c.warehouseFk + JOIN warehouse w ON w.id = c.warehouseFk JOIN tTable wt ON c.timePeriod = wt.ly - WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk + WHERE (vWarehouseFk IS NULL OR vWarehouseFk = c.warehouseFk) AND w.isComparative AND (vCountryFk IS NULL OR c.countryFk = vCountryFk) GROUP BY ai.id; - -- Genera una tabla con los datos de hace DOS años. - + -- Genera una tabla con los datos de hace 2 años CREATE OR REPLACE TEMPORARY TABLE tTwoYearsAgo (KEY (tItemFk)) ENGINE = MEMORY @@ -180,73 +177,72 @@ proc: BEGIN SUM(IF(c.timePeriod = z7, c.price, 0)) vlprice7 FROM tmp.itemInventory ai JOIN comparative c ON c.itemFk = ai.id - JOIN warehouse w on w.id = c.warehouseFk + JOIN warehouse w ON w.id = c.warehouseFk JOIN tTable wt ON c.timePeriod = wt.zy - WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk + WHERE (vWarehouseFk IS NULL OR vWarehouseFk = c.warehouseFk) AND w.isComparative AND (vCountryFk IS NULL OR c.countryFk = vCountryFk) GROUP BY ai.id; - -- Genera una tabla con los datos de este año.ss - + -- Genera una tabla con los datos de este año CREATE OR REPLACE TEMPORARY TABLE tCurrentYear (KEY (cItemFk)) ENGINE = MEMORY SELECT t.itemFk cItemFk, - SUM(IF(week = w1, total, 0)) cweek1, - SUM(IF(week = w2, total, 0)) cweek2, - SUM(IF(week = w3, total, 0)) cweek3, - SUM(IF(week = w4, total, 0)) cweek4, - SUM(IF(week = w5, total, 0)) cweek5, - SUM(IF(week = w6, total, 0)) cweek6, - SUM(IF(week = w7, total, 0)) cweek7, - SUM(IF(week = w1, price, 0)) cprice1, - SUM(IF(week = w2, price, 0)) cprice2, - SUM(IF(week = w3, price, 0)) cprice3, - SUM(IF(week = w4, price, 0)) cprice4, - SUM(IF(week = w5, price, 0)) cprice5, - SUM(IF(week = w6, price, 0)) cprice6, - SUM(IF(week = w7, price, 0)) cprice7 + SUM(IF(`week` = w1, total, 0)) cweek1, + SUM(IF(`week` = w2, total, 0)) cweek2, + SUM(IF(`week` = w3, total, 0)) cweek3, + SUM(IF(`week` = w4, total, 0)) cweek4, + SUM(IF(`week` = w5, total, 0)) cweek5, + SUM(IF(`week` = w6, total, 0)) cweek6, + SUM(IF(`week` = w7, total, 0)) cweek7, + SUM(IF(`week` = w1, price, 0)) cprice1, + SUM(IF(`week` = w2, price, 0)) cprice2, + SUM(IF(`week` = w3, price, 0)) cprice3, + SUM(IF(`week` = w4, price, 0)) cprice4, + SUM(IF(`week` = w5, price, 0)) cprice5, + SUM(IF(`week` = w6, price, 0)) cprice6, + SUM(IF(`week` = w7, price, 0)) cprice7 FROM ( SELECT s.itemFk, ti.period `week`, SUM(s.quantity) total, - TRUNCATE(SUM(s.quantity * s.priceFixed),0) price - FROM ticket t + TRUNCATE(SUM(s.quantity * s.priceFixed), 0) price + FROM ticket t FORCE INDEX (Fecha) JOIN sale s ON t.id = s.ticketFk - JOIN tmp.itemInventory it ON it.id = s.itemFk - JOIN time ti ON ti.dated = DATE(t.shipped) + JOIN tmp.itemInventory it ON it.id = s.itemFk + JOIN `time` ti ON ti.dated = DATE(t.shipped) JOIN item i ON i.id = s.itemFk JOIN itemType tp ON tp.id = i.typeFk JOIN itemCategory ic ON ic.id = tp.categoryFk JOIN warehouse w ON w.id = t.warehouseFk - STRAIGHT_JOIN address ad ON ad.id = t.addressFk - JOIN province p ON p.id = ad.provinceFk + JOIN `address` ad ON ad.id = t.addressFk + JOIN province p ON p.id = ad.provinceFk JOIN `client` c ON c.id = ad.clientFk WHERE t.shipped BETWEEN vDayRangeStart AND util.dayEnd(vDayRangeEnd) - AND c.typeFk IN ('Normal','handMaking') - AND w.id = COALESCE(vWarehouseFk, w.id) + AND c.typeFk IN ('normal', 'handMaking') + AND (vWarehouseFk IS NULL OR vWarehouseFk = w.id) + AND (vCountryFk IS NULL OR p.countryFk = vCountryFk) AND w.isComparative - AND (vCountryFk IS NULL OR p.countryFk = vCountryFk) - GROUP BY i.id, week + GROUP BY i.id, `week` ) t GROUP BY t.itemFk; - -- Genera la tabla con la comparativa. + -- Genera la tabla con la comparativa CREATE OR REPLACE TEMPORARY TABLE tmp.comparative ENGINE = MEMORY - SELECT it.subName productor, - b.packing, + SELECT it.subName productor, + b.packing, b.buyingValue costefijo, b.groupingMode caja, it.image ArticleImage, - IFNULL(it.inkFk,"?") color, + IFNULL(it.inkFk, '?') color, tp.code tipo, it.typeFk tipo_id, o.code origen, it.category categoria, it.stems tallos, - it.size medida, + it.`size` medida, it.name article, w.code codigoTrabajador, tp.categoryFk reino_id, @@ -257,24 +253,27 @@ proc: BEGIN it.id Id_Article, i.buy_id, tp.life, - IFNULL(i.sd,0) sd, + IFNULL(i.sd, 0) sd, i.avalaible, i.visible, i.buy_date, e.id provider_id, it.comment comments, it.description itemDescription, - IF(cy.cItemFk IS NULL AND i.visible = 0 AND i.avalaible = 0 - AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) filtret, + IF(cy.cItemFk IS NULL AND i.visible = 0 + AND i.avalaible = 0 AND (i.sd IS NULL OR i.sd = 0), + FALSE, + TRUE + ) filtret, IF(it.hasMinPrice, FORMAT(it.minPrice, 2), "") pvp, s.company_name FROM tmp.itemInventory i JOIN item it ON it.id = i.id - LEFT JOIN itemType tp ON tp.id = it.typeFk - LEFT JOIN worker w ON w.id = tp.workerFk + JOIN itemType tp ON tp.id = it.typeFk + JOIN worker w ON w.id = tp.workerFk LEFT JOIN buy b ON b.id = i.buy_id - LEFT JOIN entry e ON e.id = b.entryFk - LEFT JOIN origin o ON o.id = it.originFk + LEFT JOIN `entry` e ON e.id = b.entryFk + JOIN origin o ON o.id = it.originFk LEFT JOIN tLastYear ly ON ly.lItemFk = it.id LEFT JOIN tCurrentYear cy ON cy.cItemFk = it.id LEFT JOIN tTwoYearsAgo zy ON zy.tItemFk = it.id @@ -287,8 +286,8 @@ proc: BEGIN OR ly.lweek1 OR ly.lweek2 OR ly.lweek3 OR ly.lweek4 OR ly.lweek5 OR ly.lweek6 OR ly.lweek7 OR zy.vlweek1 OR zy.vlweek2 OR zy.vlweek3 OR zy.vlweek4 OR zy.vlweek5 OR zy.vlweek6 OR zy.vlweek7; - -- Elimina las tablas temporales creadas... - DROP TEMPORARY TABLE IF EXISTS tmp.itemInventory, + DROP TEMPORARY TABLE IF EXISTS + tmp.itemInventory, tTwoYearsAgo, tLastYear, tCurrentYear, diff --git a/db/routines/vn/procedures/item_devalueA2.sql b/db/routines/vn/procedures/item_devalueA2.sql new file mode 100644 index 000000000..c9f716d8f --- /dev/null +++ b/db/routines/vn/procedures/item_devalueA2.sql @@ -0,0 +1,408 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_devalueA2`( + vSelf INT, + vShelvingFK VARCHAR(10), + vBuyingValue DECIMAL(10,4), + vQuantity INT +) +BEGIN +/** + * Devalua un item modificando su calidad de A1 a A2. + * Si no existe el item A2 lo crea y genera los movimientos de las entradas + * de almacén y shelvings correspondientes + * + * @param vSelf Id de artículo a devaluar + * @param vShelvingFK Ubicación actual del artículo + * @param vBuyingValue Nuevo precio de coste + * @param vQuantity Cantidad del ítem a pasar a A2 + */ + DECLARE vItemA2Fk INT; + DECLARE vLastBuyFk BIGINT; + DECLARE vA1BuyFk INT; + DECLARE vA2BuyFk INT; + DECLARE vTargetEntryFk INT; + DECLARE vTargetEntryDate DATE; + DECLARE vTargetItemShelvingFk BIGINT; + DECLARE vWarehouseFk INT; + DECLARE vCacheFk INT; + DECLARE vLastEntryFk INT; + DECLARE vCurrentVisible INT; + DECLARE vDevalueTravelFk INT; + DECLARE vCurdate DATE; + DECLARE vBuyingValueOriginal DECIMAL(10,4); + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT TRUE FROM item WHERE id = vSelf AND (category <> 'A1' OR category IS NULL)) THEN + CALL util.throw('Item has not category A1'); + END IF; + + SELECT warehouseFk INTO vWarehouseFk + FROM userConfig + WHERE userFk = account.myUser_getId(); + + IF NOT vWarehouseFk OR vWarehouseFk IS NULL THEN + CALL util.throw ('Operator has not a valid warehouse'); + END IF; + + IF vQuantity <= 0 OR vQuantity IS NULL THEN + CALL util.throw ('The quantity is incorrect'); + END IF; + + SELECT util.VN_CURDATE() INTO vCurdate; + + SELECT t.id INTO vDevalueTravelFk + FROM travel t + JOIN travelConfig tc + WHERE t.shipped = vCurdate + AND t.landed = vCurdate + AND t.warehouseInFk = vWarehouseFk + AND t.warehouseOutFk = tc.devalueWarehouseOutFk + AND t.agencyModeFk = tc.devalueAgencyModeFk + LIMIT 1; + + IF NOT vDevalueTravelFk OR vDevalueTravelFk IS NULL THEN + INSERT INTO travel ( + shipped, + landed, + warehouseInFk, + warehouseOutFk, + `ref`, + isReceived, + agencyModeFk) + SELECT vCurdate, + vCurdate, + vWarehouseFk, + tc.devalueWarehouseOutFk, + tc.devalueRef, + TRUE, + tc.devalueAgencyModeFk + FROM travelConfig tc; + SET vDevalueTravelFk = LAST_INSERT_ID(); + END IF; + + SELECT id, DATE(dated) INTO vTargetEntryFk, vTargetEntryDate + FROM `entry` e + WHERE DATE(dated) = vCurdate + AND typeFk = 'devaluation' + AND travelFk = vDevalueTravelFk + ORDER BY created DESC + LIMIT 1; + + CALL buyUltimate(vWarehouseFk, vCurdate); + + SELECT b.entryFk, bu.buyFk,IFNULL(b.buyingValue, 0) INTO vLastEntryFk, vLastBuyFk, vBuyingValueOriginal + FROM tmp.buyUltimate bu + JOIN vn.buy b ON b.id = bu.buyFk + WHERE bu.itemFk = vSelf + AND bu.warehouseFk = vWarehouseFk; + + IF vBuyingValue > vBuyingValueOriginal THEN + CALL util.throw ('Price not valid'); + END IF; + + IF vLastEntryFk IS NULL OR vLastBuyFk IS NULL THEN + CALL util.throw ('The item has not a buy'); + END IF; + + SELECT id,visible INTO vTargetItemShelvingFk, vCurrentVisible + FROM itemShelving + WHERE shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci + AND itemFk = vSelf + LIMIT 1; + + IF vCurrentVisible IS NULL THEN + CALL util.throw ('The shelving has not a visible for this item'); + END IF; + + IF vQuantity > vCurrentVisible THEN + CALL util.throw('Quantity is greater than visible'); + END IF; + + START TRANSACTION; + + IF NOT vTargetEntryFk OR vTargetEntryFk IS NULL + OR NOT vTargetEntryDate <=> vCurdate THEN + INSERT INTO entry( + travelFk, + supplierFk, + dated, + commission, + currencyFk, + companyFk, + clonedFrom, + typeFk + ) + SELECT vDevalueTravelFk, + supplierFk, + vCurdate, + commission, + currencyFk, + companyFk, + vLastEntryFk, + 'devaluation' + FROM entry + WHERE id = vLastEntryFk; + + SET vTargetEntryFk = LAST_INSERT_ID(); + END IF; + + SELECT i.id INTO vItemA2Fk + FROM item i + JOIN ( + SELECT i.id, + i.name, + i.subname, + i.value5, + i.value6, + i.value7, + i.value8, + i.value9, + i.value10, + i.NumberOfItemsPerCask, + i.EmbalageCode, + i.quality + FROM item i + WHERE i.id = vSelf + )i2 ON i2.name <=> i.name + AND i2.subname <=> i.subname + AND i2.value5 <=> i.value5 + AND i2.value6 <=> i.value6 + AND i2.value8 <=> i.value8 + AND i2.value9 <=> i.value9 + AND i2.value10 <=> i.value10 + AND i2.NumberOfItemsPerCask <=> i.NumberOfItemsPerCask + AND i2.EmbalageCode <=> i.EmbalageCode + AND i2.quality <=> i.quality + WHERE i.id <> i2.id + AND i.category = 'A2' + LIMIT 1; + + IF vItemA2Fk IS NULL THEN + INSERT INTO item ( + equivalent, + name, + `size`, + stems, + minPrice, + isToPrint, + family, + box, + category, + originFk, + doPhoto, + image, + inkFk, + intrastatFk, + hasMinPrice, + created, + comment, + typeFk, + generic, + producerFk, + description, + density, + relevancy, + expenseFk, + isActive, + longName, + subName, + minimum, + upToDown, + supplyResponseFk, + hasKgPrice, + isFloramondo, + isFragile, + numberOfItemsPerCask, + embalageCode, + quality, + stemMultiplier, + itemPackingTypeFk, + packingOut, + genericFk, + isLaid, + lastUsed, + weightByPiece, + editorFk, + recycledPlastic, + nonRecycledPlastic) + SELECT equivalent, + name, + `size`, + stems, + minPrice, + isToPrint, + family, + box, + 'A2', + originFk, + doPhoto, + image, + inkFk, + intrastatFk, + hasMinPrice, + created, + comment, + typeFk, + generic, + producerFk, + description, + density, + relevancy, + expenseFk, + isActive, + longName, + subName, + minimum, + upToDown, + supplyResponseFk, + hasKgPrice, + isFloramondo, + isFragile, + numberOfItemsPerCask, + embalageCode, + quality, + stemMultiplier, + itemPackingTypeFk, + packingOut, + genericFk, + isLaid, + lastUsed, + weightByPiece, + editorFk, + recycledPlastic, + nonRecycledPlastic + FROM item + WHERE id = vSelf; + + SET vItemA2Fk = LAST_INSERT_ID(); + + INSERT INTO itemTag (itemFk, tagFk, `value`, intValue, priority, editorFk) + SELECT vItemA2Fk, tagFk, `value`, intValue, priority, editorFk + FROM itemTag + WHERE id = vSelf; + + UPDATE itemTaxCountry itc + JOIN itemTaxCountry itc2 ON itc2.itemFk = vSelf + AND itc2.countryFk = itc.countryFk + SET itc2.taxClassFk = itc.taxClassFk + WHERE itc.id = vItemA2Fk; + + INSERT INTO itemBotanical (itemFk, genusFk, specieFk) + SELECT vItemA2Fk, genusFk, specieFk + FROM itemBotanical + WHERE itemFk = vSelf; + END IF; + + IF vQuantity = vCurrentVisible THEN + DELETE FROM itemShelving + WHERE id = vTargetItemShelvingFk; + ELSE + UPDATE itemShelving + SET visible = vCurrentVisible - vQuantity + WHERE id = vTargetItemShelvingFk; + END IF; + + INSERT INTO buy( + entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk) + SELECT vTargetEntryFk, + itemFk, + - LEAST(vQuantity, vCurrentVisible), + buyingValue, + freightValue, + TRUE, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk + FROM vn.buy + WHERE id = vLastBuyFk + UNION + SELECT vTargetEntryFk, + vItemA2Fk, + vQuantity, + vBuyingValue, + freightValue, + TRUE, + stickers, + packagingFk, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + price1, + price2, + price3, + minPrice, + isChecked, + location, + weight, + itemOriginalFk + FROM vn.buy + WHERE id = vLastBuyFk; + + INSERT IGNORE INTO itemShelving ( + itemFk, + shelvingFk, + visible, + `grouping`, + packing, + packagingFk, + userFk, + isChecked) + SELECT vItemA2Fk, + shelvingFk, + vQuantity , + `grouping`, + packing, + packagingFk, + account.myUser_getId(), + isChecked + FROM itemShelving + WHERE itemFK = vSelf + AND shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci + ON DUPLICATE KEY UPDATE + visible = vQuantity + VALUES(visible); + + COMMIT; + CALL cache.visible_refresh(vCacheFk, TRUE, vWarehouseFk); + CALL cache.available_refresh(vCacheFk, TRUE, vWarehouseFk, vCurdate); + CALL buy_recalcPricesByBuy(vA2BuyFk); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/item_ValuateInventory.sql b/db/routines/vn/procedures/item_valuateInventory.sql similarity index 74% rename from db/routines/vn/procedures/item_ValuateInventory.sql rename to db/routines/vn/procedures/item_valuateInventory.sql index bfd96fa82..18aefdf7b 100644 --- a/db/routines/vn/procedures/item_ValuateInventory.sql +++ b/db/routines/vn/procedures/item_valuateInventory.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_ValuateInventory`(vDated DATE, vIsDetailed BOOLEAN) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_valuateInventory`( + vDated DATE +) BEGIN DECLARE vInventoried DATE; DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; @@ -15,8 +17,7 @@ BEGIN SELECT tr.landed INTO vInventoried FROM travel tr JOIN `entry` e ON e.travelFk = tr.id - JOIN entryConfig ec - WHERE landed <= vDateDayEnd + WHERE tr.landed <= vDateDayEnd AND e.supplierFk = vInventorySupplierFk ORDER BY tr.landed DESC LIMIT 1; @@ -27,8 +28,7 @@ BEGIN SELECT landed INTO vInventoryClone FROM travel tr JOIN `entry` e ON e.travelFk = tr.id - JOIN entryConfig ec - WHERE landed >= vDated + WHERE tr.landed >= vDated AND e.supplierFk = vInventorySupplierFk ORDER BY landed ASC LIMIT 1; @@ -38,13 +38,14 @@ BEGIN END IF; CREATE OR REPLACE TEMPORARY TABLE tInventory( - warehouseFk SMALLINT, - itemFk BIGINT, - quantity INT, - cost DOUBLE DEFAULT 0, - total DOUBLE DEFAULT 0, - warehouseInventory VARCHAR(20), - PRIMARY KEY (warehouseInventory, itemFk) USING HASH + warehouseFk SMALLINT, + itemFk BIGINT, + quantity INT, + volume DECIMAL(10,2), + cost DOUBLE DEFAULT 0, + total DOUBLE DEFAULT 0, + warehouseInventory VARCHAR(20), + PRIMARY KEY (warehouseInventory, itemFk) USING HASH ) ENGINE = MEMORY; @@ -60,9 +61,8 @@ BEGIN JOIN `entry` e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = warehouseInFk - JOIN entryConfig ec - WHERE landed = vDateDayEnd + JOIN warehouse w ON w.id = tr.warehouseInFk + WHERE tr.landed = vDateDayEnd AND e.supplierFk = vInventorySupplierFk AND w.valuatedInventory AND t.isInventory @@ -78,9 +78,8 @@ BEGIN JOIN `entry` e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = warehouseInFk - JOIN entryConfig ec - WHERE landed = vInventoried + JOIN warehouse w ON w.id = tr.warehouseInFk + WHERE tr.landed = vInventoried AND e.supplierFk = vInventorySupplierFk AND w.valuatedInventory AND t.isInventory @@ -99,7 +98,6 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk JOIN itemType t ON t.id = i.typeFk JOIN warehouse w ON w.id = tr.warehouseInFk - JOIN entryConfig ec WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE) AND NOT e.isRaid @@ -183,52 +181,37 @@ BEGIN AND e.isConfirmed ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity); - CALL vn.buyUltimate(NULL, vDateDayEnd); + CALL buyUltimate(NULL, vDateDayEnd); + + DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity; UPDATE tInventory i JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk JOIN buy b ON b.id = bu.buyFk - SET total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)), - cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0) - WHERE i.quantity; + LEFT JOIN itemCost ic ON ic.itemFk = i.itemFk + AND ic.warehouseFk = i.warehouseFk + SET i.total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)), + i.cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0), + i.volume = i.quantity * ic.cm3delivery / 1000000; - DELETE FROM tInventory - WHERE quantity IS NULL OR NOT quantity; - - IF vIsDetailed THEN - SELECT ti.warehouseFk, - i.id itemFk, - i.longName, - i.size, - ti.quantity, - tp.name Tipo, - ic.name Reino, - ti.cost, - CAST(ti.total AS DECIMAL(10, 2)) total, - ti.warehouseInventory almacen - FROM tInventory ti - JOIN warehouse w ON w.id = warehouseFk - JOIN item i ON i.id = ti.itemFk - JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk - WHERE w.valuatedInventory - AND ti.total > 0 - ORDER BY ti.total DESC; - ELSE - SELECT i.warehouseInventory Almacen, - ic.name Reino, - CAST(i.total AS DECIMAL(10, 2)) Euros, - w.code Comprador, - it.id - FROM tInventory i - JOIN warehouse wh ON wh.id = warehouseFk - JOIN item it ON it.id = i.itemFk - JOIN itemType itp ON itp.id = it.typeFk - LEFT JOIN worker w ON w.id = itp.workerFk - JOIN itemCategory ic ON ic.id = itp.categoryFk - WHERE wh.valuatedInventory - AND i.total > 0; - END IF; + SELECT ti.warehouseFk, + i.id, + i.longName, + i.size, + ti.quantity, + ti.volume, + tp.name itemTypeName, + ic.name itemCategoryName, + ti.cost, + ti.total, + ti.warehouseInventory + FROM tInventory ti + JOIN warehouse w ON w.id = warehouseFk + JOIN item i ON i.id = ti.itemFk + JOIN itemType tp ON tp.id = i.typeFk + JOIN itemCategory ic ON ic.id = tp.categoryFk + WHERE w.valuatedInventory + AND ti.total > 0; DROP TEMPORARY TABLE tmp.buyUltimate, diff --git a/db/routines/vn/procedures/ledger_doCompensation.sql b/db/routines/vn/procedures/ledger_doCompensation.sql index 80475ac08..391575bac 100644 --- a/db/routines/vn/procedures/ledger_doCompensation.sql +++ b/db/routines/vn/procedures/ledger_doCompensation.sql @@ -28,7 +28,7 @@ BEGIN DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - CALL ledger_next(YEAR(vDated), vNewBookEntry); + CALL ledger_nextTx(YEAR(vDated), vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client diff --git a/db/routines/vn/procedures/ledger_next.sql b/db/routines/vn/procedures/ledger_next.sql index 5cde90def..0a390ab16 100644 --- a/db/routines/vn/procedures/ledger_next.sql +++ b/db/routines/vn/procedures/ledger_next.sql @@ -1,13 +1,35 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_next`( IN vFiscalYear INT, - OUT vNewBookEntry INT + OUT vLastBookEntry INT ) +/** + * Devuelve un número de asiento válido, según el contador de asientos + * tabla vn.ledgerConfig, si no existe lo inicializa a 1 + * No inicia transacción, para transaccionar usar vn.ledger_nextTx + * + * @param vFiscalYear Id del año contable + * @return vLastBookEntry Id del asiento + */ BEGIN - UPDATE ledgerCompany - SET bookEntry = LAST_INSERT_ID(bookEntry + 1) - WHERE fiscalYear = vFiscalYear; + IF vFiscalYear IS NULL THEN + CALL util.throw('Fiscal year is required'); + END IF; - SET vNewBookEntry = LAST_INSERT_ID(); + SELECT bookEntry + 1 INTO vLastBookEntry + FROM ledgerCompany + WHERE fiscalYear = vFiscalYear + FOR UPDATE; + + IF vLastBookEntry IS NULL THEN + INSERT INTO ledgerCompany + SET fiscalYear = vFiscalYear, + bookEntry = 1; + SET vLastBookEntry = 1; + END IF; + + UPDATE ledgerCompany + SET bookEntry = vLastBookEntry + WHERE fiscalYear = vFiscalYear; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ledger_nextTx.sql b/db/routines/vn/procedures/ledger_nextTx.sql new file mode 100644 index 000000000..98c157676 --- /dev/null +++ b/db/routines/vn/procedures/ledger_nextTx.sql @@ -0,0 +1,30 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_nextTx`( + IN vFiscalYear INT, + OUT vLastBookEntry INT +) +/** + * Devuelve un número de asiento válido, según el contador de asientos + * tabla vn.ledgerConfig, si no existe lo inicializa a 1 + * Lo hace transaccionando el proceso + * + * @param vFiscalYear Id del año contable + * @return vLastBookEntry Id del asiento + */ +BEGIN + DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL util.tx_rollback(vIsRequiredTx); + RESIGNAL; + END; + + IF vFiscalYear IS NULL THEN + CALL util.throw('Fiscal year is required'); + END IF; + + CALL util.tx_start(vIsRequiredTx); + CALL ledger_next(vFiscalYear, vLastBookEntry); + CALL util.tx_commit(vIsRequiredTx); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/prepareTicketList.sql b/db/routines/vn/procedures/prepareTicketList.sql index f0f47f9a2..29c95cc9f 100644 --- a/db/routines/vn/procedures/prepareTicketList.sql +++ b/db/routines/vn/procedures/prepareTicketList.sql @@ -6,14 +6,16 @@ BEGIN (PRIMARY KEY (ticketFk)) ENGINE = MEMORY SELECT t.id ticketFk, t.clientFk - FROM vn.ticket t - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.client c ON c.id = t.clientFk + FROM ticket t + JOIN alertLevel al ON al.code = 'DELIVERED' + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + JOIN client c ON c.id = t.clientFk + WHERE c.typeFk IN ('normal','handMaking','internalUse') AND ( t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate OR ( - ts.alertLevel < 3 + ts.alertLevel < al.id AND t.shipped >= vStartingDate AND t.shipped < util.VN_CURDATE() ) diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index b42645d1e..09c01d1ef 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -67,7 +67,7 @@ proc: BEGIN wk.code salesPersonCode, p.id provinceFk, tls.productionOrder, - IFNULL(tls.alertLevel, 0) alertLevel, + IFNULL(tls.alertLevel, al.id) alertLevel, t.isBoxed palletized, IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion, tlu.lastUpdated, @@ -81,6 +81,7 @@ proc: BEGIN rm.bufferFk FROM tmp.productionTicket tt JOIN ticket t ON tt.ticketFk = t.id + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN client c ON c.id = t.clientFk @@ -101,7 +102,7 @@ proc: BEGIN LEFT JOIN parking pk ON pk.id = tp.parkingFk WHERE t.warehouseFk = vWarehouseFk AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP'); - + UPDATE tmp.productionBuffer pb JOIN ( SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking @@ -109,12 +110,12 @@ proc: BEGIN JOIN sale s ON s.ticketFk = pb.ticketFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - JOIN parking p ON p.id = sg.parkingFk + JOIN parking p ON p.id = sg.parkingFk GROUP BY pb.ticketFk ) t ON t.ticketFk = pb.ticketFk SET pb.previaParking = t.previaParking; - -- Problemas por ticket + -- Problemas por ticket ALTER TABLE tmp.productionBuffer CHANGE COLUMN `problem` `problem` VARCHAR(255), ADD COLUMN `collectionH` INT, @@ -145,13 +146,19 @@ proc: BEGIN -- Líneas y volumen por ticket UPDATE tmp.productionBuffer pb JOIN ( - SELECT tt.ticketFk, - COUNT(*) `lines`, - SUM(sv.volume) m3, - IFNULL(SUM(IF(sv.isPicked, sv.volume, 0)) / SUM(sv.volume), 0) rate - FROM tmp.productionTicket tt - JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk - GROUP BY tt.ticketFk + SELECT tt.ticketFk, + COUNT(*) `lines`, + SUM(s.quantity * ic.cm3delivery / 1000000) m3, + IFNULL(SUM(IF(s.isPicked, + (s.quantity * ic.cm3delivery / 1000000), + 0)) / SUM(s.quantity * ic.cm3delivery / 1000000), + 0) rate + FROM tmp.productionTicket tt + JOIN sale s ON s.ticketFk = tt.ticketFk + AND s.quantity > 0 + JOIN itemCost ic ON ic.itemFk = s.itemFk + AND ic.warehouseFk = vWarehouseFk + GROUP BY tt.ticketFk ) m ON m.ticketFk = pb.ticketFk SET pb.`lines` = m.`lines`, pb.m3 = m.m3, @@ -218,6 +225,8 @@ proc: BEGIN AND ish.visible GROUP BY ish.itemFk, p.sectorFk; + CREATE INDEX idxItem ON tItemShelvingStock (itemFk); + INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount) SELECT pb.ticketFk, COUNT(DISTINCT s.id) FROM tmp.productionBuffer pb diff --git a/db/routines/vn/procedures/reportLabelCollection_get.sql b/db/routines/vn/procedures/reportLabelCollection_get.sql index e7f8f2bc3..f3bcbfa28 100644 --- a/db/routines/vn/procedures/reportLabelCollection_get.sql +++ b/db/routines/vn/procedures/reportLabelCollection_get.sql @@ -47,7 +47,7 @@ BEGIN LEFT JOIN ticketTrolley tt ON tt.ticket = t.id LEFT JOIN zone zo ON t.zoneFk = zo.id LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) GROUP BY t.id ORDER BY cc.code; diff --git a/db/routines/vn/procedures/routeMonitor_calculate.sql b/db/routines/vn/procedures/routeMonitor_calculate.sql index 04a31a161..463c176ff 100644 --- a/db/routines/vn/procedures/routeMonitor_calculate.sql +++ b/db/routines/vn/procedures/routeMonitor_calculate.sql @@ -106,7 +106,7 @@ BEGIN SET rm.m3boxes = sub.m3boxes; UPDATE routesMonitor rm - JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk SET rm.etd = rs.eta; DROP TEMPORARY TABLE tmp.routesMonitor; diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index 98926b28b..9944ab0c2 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -64,10 +64,15 @@ BEGIN FROM tmp.sale_getProblems tp JOIN ticket t ON t.id = tp.ticketFk JOIN ( - SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat + SELECT t.addressFk, + SUM(ROUND(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0)) litros, + t.totalWithoutVat FROM tmp.ticket_list tl - JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk JOIN ticket t ON t.id = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id + AND s.quantity > 0 + JOIN itemCost ic ON ic.itemFk = s.itemFk + AND ic.warehouseFk = t.warehouseFk JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = util.VN_CURDATE() JOIN agencyMode am ON am.id = t.agencyModeFk @@ -95,12 +100,12 @@ BEGIN FROM ( SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk FROM tmp.ticket_list tl - JOIN vn.sale s ON s.ticketFk = tl.ticketFk - LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id - LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN sale s ON s.ticketFk = tl.ticketFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired + JOIN ticket t ON t.id = tl.ticketFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP') AND s.quantity > 0 GROUP BY s.id diff --git a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql index 895598e84..b911327dd 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql @@ -12,12 +12,15 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.sale (INDEX(saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, sale_hasComponentLack(s.id) hasProblem - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - WHERE t.shipped >= util.midnight() - AND (vComponentFk IS NULL OR sc.componentFk = vComponentFk); + SELECT saleFk, sale_hasComponentLack(saleFk)hasProblem + FROM ( + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + WHERE t.shipped >= util.VN_CURDATE() + AND (vComponentFk IS NULL OR sc.componentFk = vComponentFk) + GROUP BY s.id) sub; CALL sale_setProblem('hasComponentLack'); diff --git a/db/routines/vn/procedures/sale_setProblemRounding.sql b/db/routines/vn/procedures/sale_setProblemRounding.sql index 366fbf8fd..f14cd408f 100644 --- a/db/routines/vn/procedures/sale_setProblemRounding.sql +++ b/db/routines/vn/procedures/sale_setProblemRounding.sql @@ -20,15 +20,15 @@ BEGIN CALL buyUltimate(vWarehouseFk, vShipped); - CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf saleFk, MOD(vQuantity, bu.`grouping`) hasProblem + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem FROM tmp.buyUltimate bu JOIN buy b ON b.id = bu.buyFk WHERE bu.itemFk = vItemFk; CALL sale_setProblem('hasRounding'); - DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.sale; DROP TEMPORARY TABLE tmp.buyUltimate; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index f9d43f925..a3401843a 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -35,7 +35,7 @@ BEGIN itemFk, longName, supplier, - entryFk, + CONCAT('E',entryFk) entryFk, landed, `in`, `out`, @@ -49,16 +49,98 @@ BEGIN itemFk, longName, supplier, - 'previous', + 'E previous', vFromDated, SUM(`in`), SUM(`out`), NULL, - buyingValue + AVG(buyingValue) FROM supplierPackaging WHERE supplierFk = vSupplierFk AND landed < vFromDated GROUP BY itemFk + UNION ALL + SELECT vSupplierFk, + s.itemFk, + i.longName, + c.name, + CONCAT('T',s.ticketFk), + DATE(t.shipped), + -LEAST(s.quantity,0) `in`, + GREATEST(s.quantity,0) `out`, + t.warehouseFk, + s.price * (100 - s.discount) / 100 + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN packaging p ON p.itemFk = i.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped >= vFromDated + AND p.isPackageReturnable + UNION ALL + SELECT vSupplierFk, + s.itemFk, + i.longName, + c.name, + 'T previous', + vFromDated, + SUM(-LEAST(s.quantity,0)) `in`, + SUM(GREATEST(s.quantity,0)) `out`, + NULL, + AVG(s.price * (100 - s.discount) / 100) + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN packaging p ON p.itemFk = i.id + JOIN ticket t ON t.id = s.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped < vFromDated + AND p.isPackageReturnable + GROUP BY s.itemFk + UNION ALL + SELECT vSupplierFk, + p.itemFk, + i.longName, + c.name, + CONCAT('TP',tp.ticketFk), + DATE(t.shipped), + -LEAST(tp.quantity,0) `in`, + GREATEST(tp.quantity,0) `out`, + t.warehouseFk, + 0 + FROM ticketPackaging tp + JOIN packaging p ON p.id = tp.packagingFk + JOIN item i ON i.id = p.itemFk + JOIN ticket t ON t.id = tp.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped >= vFromDated + AND p.isPackageReturnable + UNION ALL + SELECT vSupplierFk, + p.itemFk, + i.longName, + c.name, + 'TP previous', + vFromDated, + SUM(-LEAST(tp.quantity,0)) `in`, + SUM(GREATEST(tp.quantity,0)) `out`, + NULL, + 0 + FROM ticketPackaging tp + JOIN packaging p ON p.id = tp.packagingFk + JOIN item i ON i.id = p.itemFk + JOIN ticket t ON t.id = tp.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN supplier su ON su.nif = c.fi + WHERE su.id = vSupplierFk + AND t.shipped >= vFromDated + AND p.isPackageReturnable + GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub WHERE `out` OR `in`; @@ -69,8 +151,8 @@ BEGIN supplier, entryFk, landed, - `in`, - `out`, + CAST(`in` AS DECIMAL(10,0)) `in`, + CAST(`out` AS DECIMAL(10,0)) `out`, warehouse, buyingValue, balance diff --git a/db/routines/vn/procedures/ticketGetVisibleAvailable.sql b/db/routines/vn/procedures/ticketGetVisibleAvailable.sql index 07dfa69e5..3717d57e3 100644 --- a/db/routines/vn/procedures/ticketGetVisibleAvailable.sql +++ b/db/routines/vn/procedures/ticketGetVisibleAvailable.sql @@ -7,13 +7,16 @@ BEGIN DECLARE vShipped DATE; DECLARE vWarehouse TINYINT; DECLARE vAlertLevel INT; + DECLARE vAlertLevelFree INT; - SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel + SELECT t.warehouseFk, t.shipped, ts.alertLevel, al.id + INTO vWarehouse, vShipped, vAlertLevel, vAlertLevelFree FROM ticket t + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketState ts ON ts.ticketFk = vTicket WHERE t.id = vTicket; - IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN + IF vAlertLevel IS NULL OR vAlertLevel = vAlertLevelFree THEN IF vShipped >= util.VN_CURDATE() THEN CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped); END IF; diff --git a/db/routines/vn/procedures/ticketMissed_List.sql b/db/routines/vn/procedures/ticketMissed_List.sql deleted file mode 100644 index 6b0f66e6a..000000000 --- a/db/routines/vn/procedures/ticketMissed_List.sql +++ /dev/null @@ -1,49 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketMissed_List`(vTicketFk INT) -BEGIN - - DECLARE vParkingFk INT; - DECLARE vParked DATETIME; - DECLARE vLevel INT; - DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) - INTO vLevel, vCollectionFk - FROM vn.ticketCollection - WHERE ticketFk = vTicketFk - LIMIT 1; - - SELECT created, parkingFk - INTO vParked, vParkingFk - FROM vn.ticketParking - WHERE ticketFk = vTicketFk; - - SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND ( - ( - ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) - OR - ( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,1) ) - ) - )) -- Etiquetas que no se han escaneado y ya estamos con una posterior - OR - (s.alertLevel > 1 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND tp.created < vParked - AND t.packages <=> 0); - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/ticketPackaging_add.sql b/db/routines/vn/procedures/ticketPackaging_add.sql index d669b95f5..f96068b56 100644 --- a/db/routines/vn/procedures/ticketPackaging_add.sql +++ b/db/routines/vn/procedures/ticketPackaging_add.sql @@ -27,7 +27,10 @@ BEGIN SELECT DISTINCT clientFk FROM ( SELECT clientFk, SUM(quantity) totalQuantity - FROM tmp.packagingToInvoice + FROM tmp.packagingToInvoice tpi + JOIN client c ON c.id = tpi.clientFk + LEFT JOIN supplier s ON s.nif = c.fi + WHERE s.id IS NULL GROUP BY itemFk, clientFk HAVING totalQuantity > 0)sub; diff --git a/db/routines/vn/procedures/ticketParking_findSkipped.sql b/db/routines/vn/procedures/ticketParking_findSkipped.sql index b00006ffe..7713d5b50 100644 --- a/db/routines/vn/procedures/ticketParking_findSkipped.sql +++ b/db/routines/vn/procedures/ticketParking_findSkipped.sql @@ -1,64 +1,66 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) BEGIN - + /** * Averigua los tickets que se han saltado por un error en el proceso encajado * @param vTicketFk Ticket * @param vItemPackingTypeFk Modo de encajado * @return un select con los tickets afectados - */ + */ DECLARE vParkingFk INT; DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vWagon INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) INTO vLevel, vWagon, vCollectionFk FROM vn.ticketCollection tc JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk WHERE ticketFk = vTicketFk ORDER BY c.id DESC LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk WHERE ticketFk = vTicketFk AND s.itemPackingTypeFk = vItemPackingTypeFk AND s.isPackagingArea ; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk + JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.zone z ON z.id = t.zoneFk + JOIN vn.agencyMode am ON am.id = z.agencyModeFk + JOIN vn.state s ON s.id = tst.state + JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED' + JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION' + WHERE (s.alertLevel < alPacked.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea AND ( ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) OR - ( tc.collectionFk = vCollectionFk + ( tc.collectionFk = vCollectionFk AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) ) ) ) -- Etiquetas que no se han escaneado y ya estamos con una posterior OR - (s.alertLevel > 1 + (s.alertLevel > alOnPreparation.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticketRefund_beforeUpsert.sql b/db/routines/vn/procedures/ticketRefund_beforeUpsert.sql deleted file mode 100644 index 5a0e99318..000000000 --- a/db/routines/vn/procedures/ticketRefund_beforeUpsert.sql +++ /dev/null @@ -1,18 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketRefund_beforeUpsert`(vRefundTicketFk INT, vOriginalTicketFk INT) -BEGIN - DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; - - IF vRefundTicketFk = vOriginalTicketFk THEN - CALL util.throw('Original ticket and refund ticket has same id'); - END IF; - - SELECT COUNT(*) INTO vAlreadyExists - FROM ticketRefund - WHERE refundTicketFk = vOriginalTicketFk; - - IF vAlreadyExists > 0 THEN - CALL util.throw('This ticket is already a refund'); - END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/ticketStateToday_setState.sql b/db/routines/vn/procedures/ticketStateToday_setState.sql index 73a92bbb5..bd79043b4 100644 --- a/db/routines/vn/procedures/ticketStateToday_setState.sql +++ b/db/routines/vn/procedures/ticketStateToday_setState.sql @@ -1,26 +1,29 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* Modifica el estado de un ticket de hoy - * + * * @param vTicketFk el id del ticket * @param vStateCode estado a modificar del ticket - * + * */ - + DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id + DECLARE vAlertLevelPacked INT; + + SELECT s.alertLevel, al.id + INTO vAlertLevel, vAlertLevelPacked + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + JOIN alertLevel al ON al.code = 'PACKED' WHERE tst.ticketFk = vTicketFk LIMIT 1; - - IF vAlertLevel < 2 THEN - + + IF vAlertLevel < vAlertLevelPacked THEN + CALL vn.ticket_setState(vTicketFk, vStateCode); - + END IF; END$$ diff --git a/db/routines/vn/procedures/ticketStateUpdate.sql b/db/routines/vn/procedures/ticketStateUpdate.sql deleted file mode 100644 index 4e19b7eb4..000000000 --- a/db/routines/vn/procedures/ticketStateUpdate.sql +++ /dev/null @@ -1,26 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) -BEGIN - - /* - * @deprecated:utilizar ticket_setState - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM vn.state s - JOIN vn.ticketState ts ON ts.stateFk = s.id - WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - - INSERT INTO ticketTracking(stateFk, ticketFk, userFk) - SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state - WHERE `code` = vStateCode collate utf8_unicode_ci; - - END IF; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql index 7a3170d68..20601ee49 100644 --- a/db/routines/vn/procedures/ticket_DelayTruck.sql +++ b/db/routines/vn/procedures/ticket_DelayTruck.sql @@ -13,10 +13,11 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket SELECT ticketFk FROM tmp.productionBuffer + JOIN alertLevel al ON al.code = 'FREE' WHERE shipped = util.VN_CURDATE() AND problem LIKE '%I:%' AND (HH <= vHour OR HH = vHour AND mm < vMinute) - AND alertLevel = 0; + AND alertLevel = al.id; OPEN cur1; diff --git a/db/routines/vn/procedures/ticket_setProblemFreeze.sql b/db/routines/vn/procedures/ticket_setProblemFreeze.sql index bdb32b3fe..560bce612 100644 --- a/db/routines/vn/procedures/ticket_setProblemFreeze.sql +++ b/db/routines/vn/procedures/ticket_setProblemFreeze.sql @@ -13,7 +13,7 @@ BEGIN ENGINE = MEMORY SELECT t.id ticketFk, FALSE hasProblem FROM ticket t - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vClientFk IS NULL OR t.clientFk = vClientFk); UPDATE tmp.ticket t @@ -22,7 +22,7 @@ BEGIN SET t.hasProblem = TRUE WHERE c.isFreezed; - CALL ticket_setProblem('hasTicketRequest'); + CALL ticket_setProblem('isFreezed'); DROP TEMPORARY TABLE tmp.ticket; END$$ diff --git a/db/routines/vn/procedures/ticket_setProblemRequest.sql b/db/routines/vn/procedures/ticket_setProblemRequest.sql index a5dc31472..19bba5b76 100644 --- a/db/routines/vn/procedures/ticket_setProblemRequest.sql +++ b/db/routines/vn/procedures/ticket_setProblemRequest.sql @@ -13,7 +13,7 @@ BEGIN ENGINE = MEMORY SELECT t.id ticketFk, FALSE hasProblem FROM ticket t - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vSelf IS NULL OR t.id = vSelf); UPDATE tmp.ticket t diff --git a/db/routines/vn/procedures/ticket_setProblemRisk.sql b/db/routines/vn/procedures/ticket_setProblemRisk.sql index 7c499f5ba..5f73ee838 100644 --- a/db/routines/vn/procedures/ticket_setProblemRisk.sql +++ b/db/routines/vn/procedures/ticket_setProblemRisk.sql @@ -19,7 +19,7 @@ BEGIN WHERE t.id = vSelf; CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vRisk hasProblem; + SELECT vSelf ticketFk, vHasRisk hasProblem; CALL ticket_setProblem('hasRisk'); diff --git a/db/routines/vn/procedures/ticket_setProblemRounding.sql b/db/routines/vn/procedures/ticket_setProblemRounding.sql index 272a48151..81294325c 100644 --- a/db/routines/vn/procedures/ticket_setProblemRounding.sql +++ b/db/routines/vn/procedures/ticket_setProblemRounding.sql @@ -18,17 +18,17 @@ BEGIN CALL buyUltimate(vWarehouseFk, vDated); - CREATE OR REPLACE TEMPORARY TABLE tmp.ticket + CREATE OR REPLACE TEMPORARY TABLE tmp.sale SELECT s.id saleFk , MOD(s.quantity, b.`grouping`) hasProblem FROM ticket t - JOIN sale s ON s.ticketFk = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk WHERE t.id = vSelf; CALL sale_setProblem('hasRounding'); - DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.sale; DROP TEMPORARY TABLE tmp.buyUltimate; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql index b6c2d8533..00918426b 100644 --- a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql +++ b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql @@ -14,7 +14,7 @@ BEGIN SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem FROM ticket t JOIN client c ON c.id = t.clientFk - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (c.id = vClientFk OR vClientFk IS NULL); CALL ticket_setProblem('isTaxDataChecked'); diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql index 9a7852ac5..cd1f42783 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql @@ -15,8 +15,8 @@ BEGIN WITH tickets AS( SELECT t.id ticketFk FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - WHERE t.shipped >= util.midnight() + LEFT JOIN vn.sale s ON s.ticketFk = t.id + WHERE t.shipped >= util.VN_CURDATE() AND (s.itemFk = vItemFk OR vItemFk IS NULL) GROUP BY t.id )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem diff --git a/db/routines/vn/procedures/travel_cloneWithEntries.sql b/db/routines/vn/procedures/travel_cloneWithEntries.sql index 7cf9ee5ef..e2d086fc8 100644 --- a/db/routines/vn/procedures/travel_cloneWithEntries.sql +++ b/db/routines/vn/procedures/travel_cloneWithEntries.sql @@ -24,8 +24,8 @@ BEGIN DECLARE vEvaNotes VARCHAR(255); DECLARE vDone BOOL; DECLARE vAuxEntryFk INT; - DECLARE vTx BOOLEAN DEFAULT @@in_transaction; - DECLARE vRsEntry CURSOR FOR + DECLARE vIsRequiredTx BOOLEAN DEFAULT NOT @@in_transaction; + DECLARE vRsEntry CURSOR FOR SELECT e.id FROM entry e JOIN travel t ON t.id = e.travelFk @@ -35,11 +35,11 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - CALL util.tx_rollback(vTx); + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; - CALL util.tx_start(vTx); + CALL util.tx_start(vIsRequiredTx); INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom) SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk @@ -76,6 +76,6 @@ BEGIN SET @isModeInventory = FALSE; CLOSE vRsEntry; - CALL util.tx_commit(vTx); + CALL util.tx_commit(vIsRequiredTx); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/travel_throwAwb.sql b/db/routines/vn/procedures/travel_throwAwb.sql new file mode 100644 index 000000000..1b54f8532 --- /dev/null +++ b/db/routines/vn/procedures/travel_throwAwb.sql @@ -0,0 +1,14 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_throwAwb`(vSelf INT) +BEGIN +/** + * Throws an error if travel does not have a logical AWB + * or there are several AWBs associated with the same DUA + * + * @param vSelf The travel id + */ + IF NOT travel_hasUniqueAwb(vSelf) THEN + CALL util.throw('A different AWB is found in the entries'); + END IF; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/worker_checkMultipleDevice.sql b/db/routines/vn/procedures/worker_checkMultipleDevice.sql new file mode 100644 index 000000000..00df08d49 --- /dev/null +++ b/db/routines/vn/procedures/worker_checkMultipleDevice.sql @@ -0,0 +1,24 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_checkMultipleDevice`( + vSelf INT +) +BEGIN +/** + * Verify if a worker has multiple assigned devices, + * except for freelancers. + * + * @param vUserFk worker id. + */ + DECLARE vHasPda BOOLEAN; + DECLARE vIsFreelance BOOLEAN; + DECLARE vMaxDevicesPerUser INT; + + SELECT COUNT(*) INTO vHasPda FROM deviceProductionUser WHERE userFk = vSelf; + SELECT IFNULL(isFreelance, FALSE) INTO vIsFreelance FROM worker WHERE id = vSelf; + SELECT IFNULL(maxDevicesPerUser, FALSE) INTO vMaxDevicesPerUser FROM deviceProductionConfig LIMIT 1; + + IF NOT vIsFreelance AND vHasPda > vMaxDevicesPerUser THEN + CALL util.throw('You can only have one PDA'); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/xdiario_new.sql b/db/routines/vn/procedures/xdiario_new.sql new file mode 100644 index 000000000..22a26184e --- /dev/null +++ b/db/routines/vn/procedures/xdiario_new.sql @@ -0,0 +1,64 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`xdiario_new`( + vBookNumber INT, + vDated DATE, + vSubaccount VARCHAR(12), + vAccount VARCHAR(12), + vConcept VARCHAR(25), + vDebit DOUBLE, + vCredit DOUBLE, + vEuro DOUBLE, + vSerie CHAR(1), + vInvoice VARCHAR(8), + vVat DOUBLE, + vRe DOUBLE, + vAux TINYINT, + vCompanyFk INT, + OUT vNewBookNumber INT +) +/** + * Este procedimiento se encarga de la inserción de registros en la tabla XDiario. + * Si el número de asiento (vBookNumber) no está definido, se genera uno nuevo utilizando + * vn.ledger_next. + * + * @param vBookNumber Número de asiento. Si es NULL, se generará uno nuevo. + * @param vDated Fecha utilizada para generar un nuevo número de libro si vBookNumber es NULL. + * @param vSubaccount Subcuenta para la transacción. + * @param vAccount Cuenta para la transacción. + * @param vConcept Concepto de la transacción. + * @param vDebit Monto del débito para la transacción. + * @param vCredit Monto del crédito para la transacción. + * @param vEuro Monto en euros para la transacción. + * @param vSerie Serie para la transacción. + * @param vInvoice Número de factura para la transacción. + * @param vVat Monto del IVA para la transacción. + * @param vRe Monto del RE para la transacción. + * @param vAux Variable auxiliar para la transacción. + * @param vCompanyFk Clave foránea de la compañía para la transacción. + * @return No retorna un valor, pero realiza una inserción en la tabla XDiario. + */ +BEGIN + IF vBookNumber IS NULL THEN + CALL ledger_nextTx(YEAR(vDated), vBookNumber); + END IF; + + INSERT INTO XDiario + SET ASIEN = vBookNumber, + FECHA = vDated, + SUBCTA = vSubaccount, + CONTRA = vAccount, + CONCEPTO = vConcept, + EURODEBE = vDebit, + EUROHABER = vCredit, + BASEEURO = vEuro, + SERIE = vSerie, + FACTURA = vInvoice, + IVA = vVat, + RECEQUIV = vRe, + AUXILIAR = IF(vAux = FALSE, NULL, '*'), + MONEDAUSO = 2, + empresa_id = vCompanyFk; + + SET vNewBookNumber = vBookNumber; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/buy_beforeDelete.sql b/db/routines/vn/triggers/buy_beforeDelete.sql index 85f1cf298..1bbeadec9 100644 --- a/db/routines/vn/triggers/buy_beforeDelete.sql +++ b/db/routines/vn/triggers/buy_beforeDelete.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`buy_beforeDelete` BEFORE DELETE ON `buy` FOR EACH ROW BEGIN - CALL entry_checkBooked(OLD.entryFk); + CALL entry_isEditable(OLD.entryFk); IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; diff --git a/db/routines/vn/triggers/buy_beforeInsert.sql b/db/routines/vn/triggers/buy_beforeInsert.sql index 6ad72916b..39befcaf1 100644 --- a/db/routines/vn/triggers/buy_beforeInsert.sql +++ b/db/routines/vn/triggers/buy_beforeInsert.sql @@ -15,7 +15,7 @@ trig: BEGIN LEAVE trig; END IF; - CALL entry_checkBooked(NEW.entryFk); + CALL entry_isEditable(NEW.entryFk); IF NEW.printedStickers <> 0 THEN CALL util.throw('it is not possible to create buy lines with printedstickers other than 0'); END IF; diff --git a/db/routines/vn/triggers/buy_beforeUpdate.sql b/db/routines/vn/triggers/buy_beforeUpdate.sql index 2403091c6..dc999095b 100644 --- a/db/routines/vn/triggers/buy_beforeUpdate.sql +++ b/db/routines/vn/triggers/buy_beforeUpdate.sql @@ -13,7 +13,7 @@ trig:BEGIN LEAVE trig; END IF; - CALL entry_checkBooked(OLD.entryFk); + CALL entry_isEditable(OLD.entryFk); SET NEW.editorFk = account.myUser_getId(); SELECT defaultEntry INTO vDefaultEntry diff --git a/db/routines/vn/triggers/claimRatio_afterInsert.sql b/db/routines/vn/triggers/claimRatio_afterInsert.sql new file mode 100644 index 000000000..ca618bb89 --- /dev/null +++ b/db/routines/vn/triggers/claimRatio_afterInsert.sql @@ -0,0 +1,11 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`claimRatio_afterInsert` + AFTER INSERT ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/deviceProductionUser_afterInsert.sql b/db/routines/vn/triggers/deviceProductionUser_afterInsert.sql new file mode 100644 index 000000000..3c8a9a51d --- /dev/null +++ b/db/routines/vn/triggers/deviceProductionUser_afterInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`deviceProductionUser_afterInsert` + AFTER INSERT ON `deviceProductionUser` + FOR EACH ROW +BEGIN + CALL worker_checkMultipleDevice(NEW.userFk); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/deviceProductionUser_beforeUpdate.sql b/db/routines/vn/triggers/deviceProductionUser_beforeUpdate.sql index 055f81790..7318bd99b 100644 --- a/db/routines/vn/triggers/deviceProductionUser_beforeUpdate.sql +++ b/db/routines/vn/triggers/deviceProductionUser_beforeUpdate.sql @@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`deviceProductionUser_ BEFORE UPDATE ON `deviceProductionUser` FOR EACH ROW BEGIN + + CALL worker_checkMultipleDevice(NEW.userFk); SET NEW.editorFk = account.myUser_getId(); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeDelete.sql b/db/routines/vn/triggers/entry_beforeDelete.sql index 1d2c84b9e..5b83daf77 100644 --- a/db/routines/vn/triggers/entry_beforeDelete.sql +++ b/db/routines/vn/triggers/entry_beforeDelete.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entry_beforeDelete` BEFORE DELETE ON `entry` FOR EACH ROW BEGIN - CALL entry_checkBooked(OLD.id); + CALL entry_isEditable(OLD.id); DELETE FROM buy WHERE entryFk = OLD.id; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeInsert.sql b/db/routines/vn/triggers/entry_beforeInsert.sql index c0c0aa28c..17831f1b8 100644 --- a/db/routines/vn/triggers/entry_beforeInsert.sql +++ b/db/routines/vn/triggers/entry_beforeInsert.sql @@ -7,8 +7,8 @@ BEGIN CALL supplier_checkIsActive(NEW.supplierFk); SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); - IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN - CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries'); + IF NEW.travelFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.travelFk); END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index d56db5e01..4ce2eecc2 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -9,7 +9,7 @@ BEGIN DECLARE vTotalBuy INT; IF NEW.isBooked = OLD.isBooked THEN - CALL entry_checkBooked(OLD.id); + CALL entry_isEditable(OLD.id); ELSE IF NEW.isBooked THEN SELECT COUNT(*) INTO vTotalBuy @@ -25,8 +25,8 @@ BEGIN IF NOT (NEW.travelFk <=> OLD.travelFk) THEN - IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN - CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries'); + IF NEW.travelFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.travelFk); END IF; SELECT COUNT(*) > 0 INTO vIsVirtual diff --git a/db/routines/vn/triggers/expedition_beforeInsert.sql b/db/routines/vn/triggers/expedition_beforeInsert.sql index 685de72cb..e73ed9e49 100644 --- a/db/routines/vn/triggers/expedition_beforeInsert.sql +++ b/db/routines/vn/triggers/expedition_beforeInsert.sql @@ -3,25 +3,25 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInse BEFORE INSERT ON `expedition` FOR EACH ROW BEGIN - DECLARE intcounter INT; - DECLARE vShipFk INT; + DECLARE vMaxCounter INT; SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id + SELECT IFNULL(MAX(counter),0) + 1 INTO vMaxCounter + FROM expedition e + JOIN alertLevel al ON al.code = 'DELIVERED' + JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < al.id AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; - SET NEW.`counter` = intcounter; + SET NEW.`counter` = vMaxCounter; END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/payment_beforeInsert.sql b/db/routines/vn/triggers/payment_beforeInsert.sql index 0a4cd1f12..af369a69b 100644 --- a/db/routines/vn/triggers/payment_beforeInsert.sql +++ b/db/routines/vn/triggers/payment_beforeInsert.sql @@ -9,13 +9,12 @@ BEGIN DECLARE vIsCash BOOLEAN; DECLARE vIsSupplierActive BOOLEAN; - -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH SELECT (at2.code = 'cash') INTO vIsCash FROM accounting a JOIN accountingType at2 ON at2.id = a.accountingTypeFk WHERE a.id = NEW.bankFk; - IF vIsCash THEN + IF vIsCash THEN SELECT account INTO vBankAccount FROM accounting WHERE id = NEW.bankFk; @@ -24,7 +23,7 @@ BEGIN FROM supplier WHERE id = NEW.supplierFk; - CALL ledger_next(YEAR(NEW.received), NEW.companyFk, vNewBookEntry); + CALL ledger_next(YEAR(NEW.received), vNewBookEntry); INSERT INTO XDiario ( ASIEN, diff --git a/db/routines/vn/triggers/ticketRefund_beforeInsert.sql b/db/routines/vn/triggers/ticketRefund_beforeInsert.sql index 7893f6c51..ff8ce634a 100644 --- a/db/routines/vn/triggers/ticketRefund_beforeInsert.sql +++ b/db/routines/vn/triggers/ticketRefund_beforeInsert.sql @@ -4,6 +4,5 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticketRefund_beforeIn FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - CALL ticketRefund_beforeUpsert(NEW.refundTicketFk, NEW.originalTicketFk); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql b/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql index 51c7db8f2..d809b5d99 100644 --- a/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql +++ b/db/routines/vn/triggers/ticketRefund_beforeUpdate.sql @@ -4,6 +4,5 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticketRefund_beforeUp FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - CALL ticketRefund_beforeUpsert(NEW.refundTicketFk, NEW.originalTicketFk); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/ticket_afterUpdate.sql b/db/routines/vn/triggers/ticket_afterUpdate.sql index 0ce13e0a5..1c0a8be67 100644 --- a/db/routines/vn/triggers/ticket_afterUpdate.sql +++ b/db/routines/vn/triggers/ticket_afterUpdate.sql @@ -8,7 +8,9 @@ BEGIN SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; - CALL ticket_doCmr(NEW.id); + IF NEW.cmrFk THEN + CALL ticket_doCmr(NEW.id); + END IF; END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/travel_beforeInsert.sql b/db/routines/vn/triggers/travel_beforeInsert.sql index 817bd69bb..e54a5d08b 100644 --- a/db/routines/vn/triggers/travel_beforeInsert.sql +++ b/db/routines/vn/triggers/travel_beforeInsert.sql @@ -9,8 +9,8 @@ BEGIN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); - IF NEW.awbFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.id) THEN - CALL util.throw('The AWB is incorrect, there is a different AWB in the associated entries'); + IF NEW.awbFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.id); END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index 5e43c8761..5e64ad5b3 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -33,8 +33,8 @@ BEGIN END IF; END IF; - IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.id) THEN - CALL util.throw('The AWB is incorrect, there is a different AWB in the associated entries'); + IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.id); END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/views/expeditionCommon.sql b/db/routines/vn/views/expeditionCommon.sql index d1ce80880..fcf36a7d8 100644 --- a/db/routines/vn/views/expeditionCommon.sql +++ b/db/routines/vn/views/expeditionCommon.sql @@ -8,7 +8,7 @@ AS SELECT `rs`.`id` AS `truckFk`, `t`.`routeFk` AS `routeFk`, `es`.`id` AS `scanFk`, `e`.`id` AS `expeditionFk`, - `r`.`expeditionTruckFk` AS `expeditionTruckFk`, + `r`.`roadmapStopFk` AS `roadmapStopFk`, `t`.`warehouseFk` AS `warehouseFk`, `e`.`created` AS `lastPacked`, `t`.`id` AS `ticketFk` @@ -18,7 +18,7 @@ FROM ( ( ( `vn`.`roadmapStop` `rs` - LEFT JOIN `vn`.`routesMonitor` `r` ON(`rs`.`id` = `r`.`expeditionTruckFk`) + LEFT JOIN `vn`.`routesMonitor` `r` ON(`rs`.`id` = `r`.`roadmapStopFk`) ) LEFT JOIN `vn`.`ticket` `t` ON(`r`.`routeFk` = `t`.`routeFk`) ) diff --git a/db/routines/vn/views/expeditionPallet_Print.sql b/db/routines/vn/views/expeditionPallet_Print.sql index c0b8208c3..aab725ebe 100644 --- a/db/routines/vn/views/expeditionPallet_Print.sql +++ b/db/routines/vn/views/expeditionPallet_Print.sql @@ -6,7 +6,7 @@ AS SELECT `rs2`.`description` AS `truck`, `r`.`description` AS `zone`, COUNT(`es`.`id`) AS `eti`, `ep`.`id` AS `palletFk`, - `rs`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`, + `rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`, `t`.`warehouseFk` AS `warehouseFk`, IF( `r`.`created` > `util`.`VN_CURDATE`() + INTERVAL 1 DAY, @@ -33,7 +33,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `r`.`id`) ) - LEFT JOIN `vn`.`roadmapStop` `rs2` ON(`rs2`.`id` = `rm`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs2` ON(`rs2`.`id` = `rm`.`roadmapStopFk`) ) GROUP BY `ep`.`id`, `t`.`routeFk` diff --git a/db/routines/vn/views/expeditionRoute_Monitor.sql b/db/routines/vn/views/expeditionRoute_Monitor.sql index cc1f16894..7eef40425 100644 --- a/db/routines/vn/views/expeditionRoute_Monitor.sql +++ b/db/routines/vn/views/expeditionRoute_Monitor.sql @@ -15,7 +15,7 @@ FROM ( `vn`.`route` `r` LEFT JOIN `vn`.`routesMonitor` `rm` ON(`r`.`id` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`) ) JOIN `vn`.`ticket` `t` ON(`t`.`routeFk` = `r`.`id`) ) diff --git a/db/routines/vn/views/expeditionSticker.sql b/db/routines/vn/views/expeditionSticker.sql index 05fbc42a1..ef0743527 100644 --- a/db/routines/vn/views/expeditionSticker.sql +++ b/db/routines/vn/views/expeditionSticker.sql @@ -45,7 +45,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`) ) LEFT JOIN `vn`.`beach` `b` ON(`b`.`code` = `rm`.`beachFk`) ) diff --git a/db/routines/vn/views/expeditionTicket_NoBoxes.sql b/db/routines/vn/views/expeditionTicket_NoBoxes.sql index 8acbe17fe..75218c7a9 100644 --- a/db/routines/vn/views/expeditionTicket_NoBoxes.sql +++ b/db/routines/vn/views/expeditionTicket_NoBoxes.sql @@ -13,7 +13,7 @@ FROM ( ) JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`) ) - JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) + JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`) ) WHERE `e`.`id` IS NULL AND `rs`.`eta` > `util`.`VN_CURDATE`() diff --git a/db/routines/vn/views/expeditionTruck_Control.sql b/db/routines/vn/views/expeditionTruck_Control.sql deleted file mode 100644 index 838e1f89e..000000000 --- a/db/routines/vn/views/expeditionTruck_Control.sql +++ /dev/null @@ -1,19 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`expeditionTruck_Control` -AS SELECT `e`.`truckFk` AS `id`, - `e`.`eta` AS `ETD`, - `e`.`description` AS `description`, - COUNT( - DISTINCT IF(`e`.`expeditionFk` IS NULL, `e`.`ticketFk`, NULL) - ) AS `ticketsSinBultos`, - COUNT(DISTINCT `e`.`palletFk`) AS `pallets`, - COUNT(DISTINCT `e`.`routeFk`) AS `routes`, - COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`expeditionFk`) AS `expeditions`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - max(`e`.`lastPacked`) AS `lastPacked` -FROM `vn`.`expeditionCommon` `e` -GROUP BY `e`.`truckFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, - `e`.`eta` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail.sql b/db/routines/vn/views/expeditionTruck_Control_Detail.sql deleted file mode 100644 index 96a5b78e6..000000000 --- a/db/routines/vn/views/expeditionTruck_Control_Detail.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`expeditionTruck_Control_Detail` -AS SELECT `e`.`truckFk` AS `id`, - `e`.`eta` AS `eta`, - `e`.`description` AS `destino`, - `e`.`palletFk` AS `pallet`, - COUNT(DISTINCT `e`.`routeFk`) AS `routes`, - COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`expeditionTruckFk`) AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - max(`e`.`lastPacked`) AS `lastPacked` -FROM `vn`.`expeditionCommon` `e` -GROUP BY `e`.`truckFk`, - `e`.`palletFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, - `e`.`eta`, - `e`.`truckFk` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql deleted file mode 100644 index 3f239432d..000000000 --- a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql +++ /dev/null @@ -1,22 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`expeditionTruck_Control_Detail_Pallet` -AS SELECT `e`.`truckFk` AS `id`, - `e`.`eta` AS `eta`, - `e`.`description` AS `destino`, - `e`.`palletFk` AS `pallet`, - `e`.`routeFk` AS `route`, - COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - `rs`.`description` AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - `e`.`expeditionTruckFk` AS `expeditionTruckFk`, - max(`e`.`lastPacked`) AS `lastPacked` -FROM ( - `vn`.`expeditionCommon` `e` - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`expeditionTruckFk`) - ) -GROUP BY `e`.`truckFk`, - `e`.`palletFk`, - `e`.`routeFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, - `e`.`palletFk` diff --git a/db/routines/vn/views/ticketPreviousPreparingList.sql b/db/routines/vn/views/ticketPreviousPreparingList.sql index 9c84b8af3..cd18b3a7c 100644 --- a/db/routines/vn/views/ticketPreviousPreparingList.sql +++ b/db/routines/vn/views/ticketPreviousPreparingList.sql @@ -20,7 +20,7 @@ FROM ( `vn`.`saleGroup` `sg` JOIN `vn`.`saleGroupDetail` `sgd` ON(`sgd`.`saleGroupFk` = `sg`.`id`) ) - JOIN `vn`.`sale` `s` ON(`s`.`id` = `sgd`.`saleFk`) + JOIN `vn`.`sale` `s` FORCE INDEX (PRIMARY) ON(`s`.`id` = `sgd`.`saleFk`) ) JOIN `vn`.`ticketState` `tls` ON(`tls`.`ticketFk` = `s`.`ticketFk`) ) diff --git a/db/routines/vn2008/views/Compres.sql b/db/routines/vn2008/views/Compres.sql index 557136192..b99dd2b73 100644 --- a/db/routines/vn2008/views/Compres.sql +++ b/db/routines/vn2008/views/Compres.sql @@ -28,6 +28,5 @@ AS SELECT `c`.`id` AS `Id_Compra`, `c`.`workerFk` AS `Id_Trabajador`, `c`.`weight` AS `weight`, `c`.`dispatched` AS `dispatched`, - `c`.`containerFk` AS `container_id`, `c`.`itemOriginalFk` AS `itemOriginalFk` FROM `vn`.`buy` `c` diff --git a/db/routines/vn2008/views/Saldos_Prevision.sql b/db/routines/vn2008/views/Saldos_Prevision.sql deleted file mode 100644 index f4749d30f..000000000 --- a/db/routines/vn2008/views/Saldos_Prevision.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Saldos_Prevision` -AS SELECT `fb`.`id` AS `Saldos_Prevision_id`, - `fb`.`description` AS `Descripcion`, - `fb`.`amount` AS `Importe`, - `fb`.`dated` AS `Fecha`, - `fb`.`accountingFk` AS `Id_Banco`, - `fb`.`companyFk` AS `empresa_id` -FROM `vn`.`forecastedBalance` `fb` \ No newline at end of file diff --git a/db/routines/vn2008/views/Tickets.sql b/db/routines/vn2008/views/Tickets.sql index c24b87b72..59dcb9100 100644 --- a/db/routines/vn2008/views/Tickets.sql +++ b/db/routines/vn2008/views/Tickets.sql @@ -21,7 +21,6 @@ AS SELECT `t`.`id` AS `Id_Ticket`, `t`.`workerFk` AS `Id_Trabajador`, `t`.`observations` AS `Observaciones`, `t`.`isSigned` AS `Firmado`, - `t`.`isLabeled` AS `Etiquetasemitidas`, `t`.`isPrinted` AS `PedidoImpreso`, `t`.`hour` AS `Hora`, `t`.`isBlocked` AS `blocked`, diff --git a/db/versions/10955-orangeRuscus/00-firstScript.sql b/db/versions/10955-orangeRuscus/00-firstScript.sql new file mode 100644 index 000000000..745c058bf --- /dev/null +++ b/db/versions/10955-orangeRuscus/00-firstScript.sql @@ -0,0 +1,17 @@ +INSERT IGNORE INTO vn.entryType (code, description) + VALUES ('devaluation', 'Devaluación'); + +ALTER TABLE vn.travelConfig ADD IF NOT EXISTS devalueWarehouseOutFk SMALLINT(6) UNSIGNED NULL + COMMENT 'Datos del travel para las entradas generadas al devaluar artículos de A1 a A2'; + +ALTER TABLE vn.travelConfig ADD IF NOT EXISTS devalueAgencyModeFk INT(11) NULL; +ALTER TABLE vn.travelConfig ADD IF NOT EXISTS devalueRef varchar(20) NULL; + +ALTER TABLE vn.travelConfig DROP FOREIGN KEY IF EXISTS travelConfig_agencyMode_FK; + +ALTER TABLE vn.travelConfig ADD CONSTRAINT travelConfig_agencyMode_FK + FOREIGN KEY (devalueAgencyModeFk) REFERENCES vn.agencyMode(id) ON DELETE SET NULL ON UPDATE CASCADE; + +ALTER TABLE vn.travelConfig DROP FOREIGN KEY IF EXISTS travelConfig_warehouse_FK; +ALTER TABLE vn.travelConfig ADD CONSTRAINT travelConfig_warehouse_FK + FOREIGN KEY (devalueWarehouseOutFk) REFERENCES vn.warehouse(id) ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/db/versions/10978-wheatMoss/00-firstScript.sql b/db/versions/10978-wheatMoss/00-firstScript.sql new file mode 100644 index 000000000..39bf1c318 --- /dev/null +++ b/db/versions/10978-wheatMoss/00-firstScript.sql @@ -0,0 +1,4 @@ +-- Place your SQL code here +INSERT INTO salix.defaultViewConfig +(tableCode, `columns`) +VALUES('routesList', '{"ID":true,"worker":true,"agency":true,"vehicle":true,"date":true,"volume":true,"description":true,"started":true,"finished":true,"actions":true}'); diff --git a/db/versions/11010-blackChrysanthemum/00-firstScript.sql b/db/versions/11010-blackChrysanthemum/00-firstScript.sql new file mode 100644 index 000000000..c8dce54b2 --- /dev/null +++ b/db/versions/11010-blackChrysanthemum/00-firstScript.sql @@ -0,0 +1,21 @@ +ALTER TABLE vn.deviceProductionUser DROP INDEX IF EXISTS deviceProductionUser_UN; + +ALTER TABLE vn.deviceProductionUser DROP FOREIGN KEY IF EXISTS deviceProductionUser_FK; + +ALTER TABLE vn.deviceProductionUser DROP PRIMARY KEY; + +ALTER TABLE vn.deviceProductionUser ADD IF NOT EXISTS id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY FIRST; + +ALTER TABLE vn.deviceProductionUser ADD CONSTRAINT deviceProductionUser_deviceProduction_FK FOREIGN KEY IF NOT EXISTS (deviceProductionFk) REFERENCES vn.deviceProduction(id); + +ALTER TABLE vn.deviceProductionUser ADD CONSTRAINT deviceProductionUser_unique UNIQUE KEY IF NOT EXISTS (deviceProductionFk); + +ALTER TABLE vn.deviceProductionUser ADD IF NOT EXISTS simSerialNumber TEXT NULL; + +ALTER TABLE vn.deviceProductionConfig ADD IF NOT EXISTS maxDevicesPerUser INT UNSIGNED NULL; + +UPDATE vn.deviceProductionConfig SET maxDevicesPerUser=1 WHERE id=1; + +INSERT IGNORE INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Worker','getAvailablePda','READ','ALLOW','ROLE','hr'); + diff --git a/db/versions/11015-silverBamboo/00-photoMotivation.sql b/db/versions/11015-silverBamboo/00-photoMotivation.sql new file mode 100644 index 000000000..366694e12 --- /dev/null +++ b/db/versions/11015-silverBamboo/00-photoMotivation.sql @@ -0,0 +1 @@ +ALTER TABLE vn.item ADD COLUMN photoMotivation VARCHAR(255); \ No newline at end of file diff --git a/db/versions/11050-wheatAnthurium/00-firstScript.sql b/db/versions/11050-wheatAnthurium/00-firstScript.sql new file mode 100644 index 000000000..cb8034ff5 --- /dev/null +++ b/db/versions/11050-wheatAnthurium/00-firstScript.sql @@ -0,0 +1,4 @@ +-- Place your SQL code here + +ALTER TABLE floranet.catalogue ADD addressFk int(11) NOT NULL; +ALTER TABLE floranet.catalogue ADD CONSTRAINT catalogue_address_FK FOREIGN KEY (addressFk) REFERENCES vn.address(id) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/db/versions/11050-wheatAnthurium/01-elementFilter.sql b/db/versions/11050-wheatAnthurium/01-elementFilter.sql new file mode 100644 index 000000000..3f2bb78ac --- /dev/null +++ b/db/versions/11050-wheatAnthurium/01-elementFilter.sql @@ -0,0 +1,6 @@ +ALTER TABLE floranet.builder DROP FOREIGN KEY builder_FK_1; +ALTER TABLE floranet.`element` DROP PRIMARY KEY; +ALTER TABLE floranet.`element` ADD id INT NOT NULL; +ALTER TABLE floranet.`element` ADD CONSTRAINT element_pk PRIMARY KEY (id); +ALTER TABLE floranet.builder ADD CONSTRAINT builder_element_FK FOREIGN KEY (elementFk) REFERENCES floranet.`element`(id) ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/db/versions/11055-wheatPaniculata/00-firstScript.sql b/db/versions/11055-wheatPaniculata/00-firstScript.sql new file mode 100644 index 000000000..6eec62fd8 --- /dev/null +++ b/db/versions/11055-wheatPaniculata/00-firstScript.sql @@ -0,0 +1,5 @@ +ALTER TABLE vn.clientConfig + ADD monthsToDisableUser int(10) unsigned DEFAULT NULL NULL; + +UPDATE IGNORE vn.clientConfig + SET monthsToDisableUser = 12; \ No newline at end of file diff --git a/db/versions/11057-chocolateMoss/00-part.sql b/db/versions/11057-chocolateMoss/00-part.sql new file mode 100644 index 000000000..bd6c69955 --- /dev/null +++ b/db/versions/11057-chocolateMoss/00-part.sql @@ -0,0 +1,26 @@ +DROP TABLE IF EXISTS vn2008.scanTree__; +DROP TABLE IF EXISTS vn2008.payroll_embargos__; +DROP TABLE IF EXISTS vn2008.unary_source__; +DROP TABLE IF EXISTS vn2008.unary_scan_line_buy__; +DROP TABLE IF EXISTS vn2008.unary_scan_line__; +DROP TABLE IF EXISTS vn2008.unary_scan__; +DROP TABLE IF EXISTS vn2008.scan_line__; +DROP TABLE IF EXISTS vn2008.Familias__; +DROP TABLE IF EXISTS vn2008.language__; +DROP TABLE IF EXISTS vn2008.Clientes_dits__; +DROP TABLE IF EXISTS vn2008.unary_scan_line_expedition__; +DROP TABLE IF EXISTS vn2008.warehouse_group__; +DROP TABLE IF EXISTS vn2008.Espionajes__; +DROP TABLE IF EXISTS vn2008.jerarquia__; +DROP TABLE IF EXISTS vn2008.wks__; +DROP TABLE IF EXISTS vn2008.Proveedores_comunicados__; +DROP TABLE IF EXISTS vn2008.integra2_escala__; +DROP TABLE IF EXISTS vn2008.cp__; +DROP TABLE IF EXISTS vn2008.unary__; +DROP TABLE IF EXISTS vn2008.Estados__; +DROP TABLE IF EXISTS vn2008.agency_hour__; +DROP TABLE IF EXISTS vn2008.Reservas__; +DROP TABLE IF EXISTS vn2008.cyc_declaration__; +DROP TABLE IF EXISTS vn2008.route__; +DROP TABLE IF EXISTS vn2008.Proveedores_escritos__; +DROP TABLE IF EXISTS vn2008.config__; diff --git a/db/versions/11057-chocolateMoss/01-part.sql b/db/versions/11057-chocolateMoss/01-part.sql new file mode 100644 index 000000000..59df77f20 --- /dev/null +++ b/db/versions/11057-chocolateMoss/01-part.sql @@ -0,0 +1,41 @@ +DROP TABLE IF EXISTS vn2008.form_query__; +DROP TABLE IF EXISTS vn2008.filtros__; +DROP TABLE IF EXISTS vn2008.Objetivos__; +UPDATE IGNORE vn.province + SET zoneFk = NULL + WHERE zoneFk IN ( + SELECT zoneFk + FROM vn.province + WHERE zoneFk IS NOT NULL AND zoneFk NOT IN (SELECT id FROM vn.`zone`) + ); +ALTER TABLE vn.province DROP FOREIGN KEY province_zone_fk; +ALTER TABLE vn.province MODIFY COLUMN zoneFk int(11) DEFAULT NULL NULL; +ALTER TABLE vn.province ADD CONSTRAINT + province_zone_FK FOREIGN KEY (zoneFk) REFERENCES vn.`zone`(id) ON DELETE CASCADE ON UPDATE CASCADE; +DROP TABLE IF EXISTS vn2008.zones__; +DROP TABLE IF EXISTS vn2008.rec_translator__; +DROP TABLE IF EXISTS vn2008.warehouse_joined__; +DROP TABLE IF EXISTS vn2008.warehouse_filtro__; +DROP TABLE IF EXISTS vn2008.viaxpress__; +DROP TABLE IF EXISTS vn2008.cl_que__; +DROP TABLE IF EXISTS vn2008.Recibos_recorded__; +RENAME TABLE vn.coolerPathDetail TO vn.coolerPathDetail__; +ALTER TABLE vn.coolerPathDetail__ DROP FOREIGN KEY coolerPathDetail_FK; +DROP TABLE IF EXISTS vn2008.cooler_path__; +DROP TABLE IF EXISTS vn2008.payrroll_apEmpresarial__; +DROP TABLE IF EXISTS vn2008.Compres_ok__; +DROP TABLE IF EXISTS vn2008.Movimientos_avisar__; +DROP TABLE IF EXISTS vn2008.Clases__; +DROP TABLE IF EXISTS vn2008.payroll_basess__; +DROP TABLE IF EXISTS vn2008.payroll_tipobasess__; +DROP TABLE IF EXISTS vn2008.guillen__; +DROP TABLE IF EXISTS vn2008.guillen_carry__; +DROP TABLE IF EXISTS vn2008.Series__; +DROP TABLE IF EXISTS vn2008.Permisos__; +ALTER TABLE vn.buy DROP FOREIGN KEY buy_FK_1; +DROP TABLE IF EXISTS vn2008.container__; +DROP TABLE IF EXISTS vn2008.travel_reserve__; +DROP TABLE IF EXISTS vn2008.tmpNEWTARIFAS__; +DROP TABLE IF EXISTS vn2008.Clientes_potenciales__; +DROP TABLE IF EXISTS vn2008.duaDismissed__; +DROP TABLE IF EXISTS vn2008.cl_pet__; diff --git a/db/versions/11057-chocolateMoss/02-part.sql b/db/versions/11057-chocolateMoss/02-part.sql new file mode 100644 index 000000000..46cda539a --- /dev/null +++ b/db/versions/11057-chocolateMoss/02-part.sql @@ -0,0 +1,27 @@ +DROP TABLE IF EXISTS vn2008.expeditions_deleted__; +DROP TABLE IF EXISTS vn2008.Tipos_f11__; +DROP TABLE IF EXISTS vn2008.commission__; +DROP TABLE IF EXISTS vn2008.Movimientos_revisar__; +DROP TABLE IF EXISTS vn2008.recibida_agricola__; +DROP TABLE IF EXISTS vn2008.tipsa__; +DROP TABLE IF EXISTS vn2008.rounding__; +DROP TABLE IF EXISTS vn2008.Informes__; +DROP TABLE IF EXISTS vn2008.Monitoring__; +DROP TABLE IF EXISTS vn2008.Forms__; +DROP TABLE IF EXISTS vn2008.Clientes_event__; +DROP TABLE IF EXISTS vn2008.wh_selection__; +DROP TABLE IF EXISTS vn2008.template_bionic_component__; +DROP TABLE IF EXISTS vn2008.Agencias_province__; +DROP TABLE IF EXISTS vn2008.travel_pattern__; +DROP TABLE IF EXISTS vn2008.sort_merge_results_ernesto__; +DROP TABLE IF EXISTS vn2008.Conteo__; +DROP TABLE IF EXISTS vn2008.Consignatarios_devices__; +DROP TABLE IF EXISTS vn2008.link__; +DROP TABLE IF EXISTS vn2008.agency_warehouse__; +DROP TABLE IF EXISTS vn2008.warehouse_lc__; +DROP TABLE IF EXISTS vn2008.emp_day_pay__; +DROP TABLE IF EXISTS vn2008.Entradas_kop__; +DROP TABLE IF EXISTS vn2008.dock__; +DROP TABLE IF EXISTS vn2008.unaryScanFilter__; +DROP TABLE IF EXISTS vn2008.Grupos__; +DROP TABLE IF EXISTS vn2008.nichos__; diff --git a/db/versions/11057-chocolateMoss/03-part.sql b/db/versions/11057-chocolateMoss/03-part.sql new file mode 100644 index 000000000..e1947f064 --- /dev/null +++ b/db/versions/11057-chocolateMoss/03-part.sql @@ -0,0 +1,26 @@ +DROP TABLE IF EXISTS vn2008.preparation_exception__; +DROP TABLE IF EXISTS vn2008.Clientes_empresa__; +DROP TABLE IF EXISTS vn2008.call_information__; +DROP TABLE IF EXISTS vn2008.template_bionic_price__; +DROP TABLE IF EXISTS vn2008.invoice_observation__; +DROP TABLE IF EXISTS vn2008.edi_testigos__; +DROP TABLE IF EXISTS vn2008.cl_dep__; +DROP TABLE IF EXISTS vn2008.agencia_descuadre__; +DROP TABLE IF EXISTS vn2008.payroll_datos__; +DROP TABLE IF EXISTS vn2008.tblIVA__; +DROP TABLE IF EXISTS vn2008.cyc__; +DROP TABLE IF EXISTS vn2008.Tickets_stack__; +DROP TABLE IF EXISTS vn2008.config_host_forms__; +DROP TABLE IF EXISTS vn2008.template_bionic_lot__; +DROP TABLE IF EXISTS vn2008.payroll_bonificaciones__; +DROP TABLE IF EXISTS vn2008.widget__; +DROP TABLE IF EXISTS vn2008.accion_dits__; +DROP TABLE IF EXISTS vn2008.credit_card__; +DROP TABLE IF EXISTS vn2008.Brasa__; +DROP TABLE IF EXISTS vn2008.Jefes__; +DROP TABLE IF EXISTS vn2008.call_option__; +DROP TABLE IF EXISTS vn2008.expeditions_pictures__; +DROP TABLE IF EXISTS vn2008.scan__; +DROP TABLE IF EXISTS vn2008.trolley__; +DROP TABLE IF EXISTS vn2008.transport__; +DROP TABLE IF EXISTS vn2008.Baldas__; diff --git a/db/versions/11058-aquaCataractarum/00-firstScript.sql b/db/versions/11058-aquaCataractarum/00-firstScript.sql new file mode 100644 index 000000000..98fc910ad --- /dev/null +++ b/db/versions/11058-aquaCataractarum/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +ALTER TABLE floranet.`order` ADD IF NOT EXISTS observations TEXT NULL; diff --git a/db/versions/11059-crimsonAnthurium/00-firstScript.sql b/db/versions/11059-crimsonAnthurium/00-firstScript.sql new file mode 100644 index 000000000..b0eade302 --- /dev/null +++ b/db/versions/11059-crimsonAnthurium/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('RouteConfig','*','READ','ALLOW','ROLE','employee'); diff --git a/db/versions/11060-tealGalax/00-createRoleReviewer.sql b/db/versions/11060-tealGalax/00-createRoleReviewer.sql new file mode 100644 index 000000000..bf2984702 --- /dev/null +++ b/db/versions/11060-tealGalax/00-createRoleReviewer.sql @@ -0,0 +1,46 @@ +use account; + +INSERT INTO role + SET name = 'reviewer', + description = 'Revisor de producción', + hasLogin = TRUE, + created = util.VN_CURDATE(), + modified = util.VN_CURDATE(), + editorFk = NULL; + +INSERT INTO roleInherit( + role, + inheritsFrom +) + SELECT r1.id, + r2.id + FROM role r1 + JOIN role r2 + WHERE r1.name = 'reviewer' + AND r2.name = 'production' + UNION + SELECT ri.role, + r2.id + FROM roleInherit ri + JOIN role r1 ON r1.id = ri.role + JOIN role r2 ON r2.name = 'reviewer' + WHERE r1.name IN ('claimManager', 'productionBoss') + GROUP BY ri.role; + +DELETE ri + FROM roleInherit ri + JOIN role r1 ON ri.role = r1.id + JOIN role r2 ON ri.inheritsFrom = r2.id + WHERE r1.name = 'replenisher' + AND r2.name = 'buyer'; + +UPDATE salix.ACL + SET principalId = 'reviewer' + WHERE property = 'isInPreparing'; + +UPDATE user u + JOIN vn.workerDepartment wd ON wd.workerFk = u.id + JOIN vn.department d ON wd.departmentFk = d.id + JOIN role r ON r.name = 'reviewer' + SET u.role = r.id + WHERE d.name IN ('REVISION', 'PREVIA'); \ No newline at end of file diff --git a/db/versions/11061-silverMastic/00-firstScript.sql b/db/versions/11061-silverMastic/00-firstScript.sql new file mode 100644 index 000000000..32dbc0c2e --- /dev/null +++ b/db/versions/11061-silverMastic/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.buy CHANGE containerFk containerFk__ smallint(5) unsigned DEFAULT NULL NULL; diff --git a/db/versions/11063-purpleAnthurium/00-roadmapAddress.sql b/db/versions/11063-purpleAnthurium/00-roadmapAddress.sql new file mode 100644 index 000000000..6435da1c9 --- /dev/null +++ b/db/versions/11063-purpleAnthurium/00-roadmapAddress.sql @@ -0,0 +1,8 @@ +CREATE TABLE `vn`.`roadmapAddress` ( + addressFk int(11) NULL, + isActive TINYINT DEFAULT 1 NULL, + PRIMARY KEY (addressFk) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Direcciones de los troncales'; + +ALTER TABLE vn.roadmapAddress + ADD CONSTRAINT roadmapAddress_address_FK FOREIGN KEY (addressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11063-purpleAnthurium/01-roadmapStop.sql b/db/versions/11063-purpleAnthurium/01-roadmapStop.sql new file mode 100644 index 000000000..844abf45f --- /dev/null +++ b/db/versions/11063-purpleAnthurium/01-roadmapStop.sql @@ -0,0 +1,7 @@ +ALTER TABLE vn.roadmapStop DROP FOREIGN KEY expeditionTruck_FK_1; +ALTER TABLE vn.roadmapStop DROP COLUMN warehouseFk; +ALTER TABLE vn.roadmapStop ADD addressFk int(11) NULL; +ALTER TABLE vn.roadmapStop CHANGE addressFk addressFk int(11) DEFAULT NULL NULL AFTER roadmapFk; + +ALTER TABLE vn.roadmapStop + ADD CONSTRAINT roadmapStop_roadmapAddress_FK FOREIGN KEY (addressFk) REFERENCES vn.roadmapAddress(addressFk) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql b/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql new file mode 100644 index 000000000..bba1c019c --- /dev/null +++ b/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql @@ -0,0 +1,11 @@ +DELETE FROM salix.ACL + WHERE model in ('expeditionTruck', 'Roadmap', 'roadmapStop', 'roadmapAddress'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES + ('RoadmapAddress', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('RoadmapAddress', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('Roadmap', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('Roadmap', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('RoadmapStop', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('RoadmapStop', '*', 'READ', 'ALLOW', 'ROLE', 'production'); diff --git a/db/versions/11065-yellowChrysanthemum/00-modifyInvoiceInPrivileges.sql b/db/versions/11065-yellowChrysanthemum/00-modifyInvoiceInPrivileges.sql new file mode 100644 index 000000000..b65ca1c17 --- /dev/null +++ b/db/versions/11065-yellowChrysanthemum/00-modifyInvoiceInPrivileges.sql @@ -0,0 +1,24 @@ +REVOKE UPDATE ON vn. invoiceIn FROM administrative, hrBoss, buyer, logistic; +GRANT UPDATE (id, + serialNumber, + serial, + supplierFk, + issued, + supplierRef, + currencyFk, + created, + companyFk, + docFk, + booked, + operated, + siiTypeInvoiceInFk, + cplusRectificationTypeFk, + cplusSubjectOpFk, + cplusTaxBreakFk, + siiTrascendencyInvoiceInFk, + bookEntried, + isVatDeductible, + withholdingSageFk, + expenseFkDeductible, + editorFk +) ON vn.invoiceIn TO administrative, hrBoss, buyer, logistic; \ No newline at end of file diff --git a/db/versions/11065-yellowChrysanthemum/01-modifyInvoiceInAcls.sql b/db/versions/11065-yellowChrysanthemum/01-modifyInvoiceInAcls.sql new file mode 100644 index 000000000..5475b70ac --- /dev/null +++ b/db/versions/11065-yellowChrysanthemum/01-modifyInvoiceInAcls.sql @@ -0,0 +1,23 @@ +UPDATE salix.ACL + SET accessType = 'READ' + WHERE principalId IN ('administrative','buyer') + AND model = 'invoiceIn' + AND property = '*'; + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES + ('InvoiceIn', 'updateInvoiceIn', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'clone', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'corrective', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'exchangeRateUpdate', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'invoiceInEmail', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'toBook', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'toUnbook', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'updateInvoiceIn', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('InvoiceIn', 'clone', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('InvoiceIn', 'corrective', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('InvoiceIn', 'exchangeRateUpdate', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('InvoiceIn', 'invoiceInEmail', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('InvoiceIn', 'toBook', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('InvoiceIn', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'buyer'); diff --git a/db/versions/11068-blueGerbera/00-firstScript.sql b/db/versions/11068-blueGerbera/00-firstScript.sql new file mode 100644 index 000000000..6342981a7 --- /dev/null +++ b/db/versions/11068-blueGerbera/00-firstScript.sql @@ -0,0 +1,9 @@ +-- Place your SQL code here +CREATE OR REPLACE TABLE floranet.config ( + email varchar(255) DEFAULT 'floranet@verdnatura.es' NOT NULL +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; + + diff --git a/db/versions/11069-brownChrysanthemum/00-firstScript.sql b/db/versions/11069-brownChrysanthemum/00-firstScript.sql new file mode 100644 index 000000000..3220d1257 --- /dev/null +++ b/db/versions/11069-brownChrysanthemum/00-firstScript.sql @@ -0,0 +1,35 @@ +-- Place your SQL code here +DROP TABLE IF EXISTS floranet.builder; + +CREATE OR REPLACE TABLE floranet.`element` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(30) NOT NULL, + `itemFk` int(11) DEFAULT NULL, + `longNameFilter` varchar(30) DEFAULT NULL, + `typeFk` smallint(5) unsigned DEFAULT NULL, + `minSize` int(10) unsigned DEFAULT NULL, + `maxSize` int(10) unsigned DEFAULT NULL, + `inkFk` char(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `originFk` tinyint(2) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `element_FK` (`itemFk`), + KEY `element_FK_1` (`typeFk`), + KEY `element_FK_2` (`inkFk`), + KEY `element_FK_3` (`originFk`), + CONSTRAINT `element_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `element_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `element_FK_2` FOREIGN KEY (`inkFk`) REFERENCES `vn`.`ink` (`id`) ON UPDATE CASCADE, + CONSTRAINT `element_FK_3` FOREIGN KEY (`originFk`) REFERENCES `vn`.`origin` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Filtro para localizar posibles items que coincidan con la descripción'; + +CREATE OR REPLACE TABLE floranet.`recipe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `elementFk` int(11) NOT NULL, + `quantity` int(10) unsigned NOT NULL DEFAULT 1, + PRIMARY KEY (`id`), + KEY `recipe_FK` (`itemFk`), + KEY `recipe_FK_1` (`elementFk`), + CONSTRAINT `recipe_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `recipe_element_FK` FOREIGN KEY (`elementFk`) REFERENCES `element` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Links handmade products with their elements'; diff --git a/db/versions/11070-turquoiseCordyline/00-firstScript.sql b/db/versions/11070-turquoiseCordyline/00-firstScript.sql new file mode 100644 index 000000000..db123eb55 --- /dev/null +++ b/db/versions/11070-turquoiseCordyline/00-firstScript.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.routesMonitor CHANGE expeditionTruckFk roadmapStopFk int(11) DEFAULT NULL NULL; + +ALTER TABLE vn.routesMonitor ADD COLUMN expeditionTruckFk int(11) AS (roadmapStopFk) VIRTUAL; \ No newline at end of file diff --git a/db/versions/11071-turquoiseMoss/00-firstScript.sql b/db/versions/11071-turquoiseMoss/00-firstScript.sql new file mode 100644 index 000000000..f1de5987f --- /dev/null +++ b/db/versions/11071-turquoiseMoss/00-firstScript.sql @@ -0,0 +1,5 @@ +-- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('RoadmapStop','*','*','ALLOW','ROLE','production'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); diff --git a/db/versions/11074-brownRuscus/00-firstScript.sql b/db/versions/11074-brownRuscus/00-firstScript.sql new file mode 100644 index 000000000..f78ba98ae --- /dev/null +++ b/db/versions/11074-brownRuscus/00-firstScript.sql @@ -0,0 +1,20 @@ +-- Place your SQL code here + + +-- floranet.recipe definition + +CREATE OR REPLACE TABLE floranet.`recipe` + ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL COMMENT 'Bouquet or plant name', + `elementFk` int(11) NOT NULL COMMENT 'Item detail for bouquet''s composition', + `quantity` int(10) unsigned NOT NULL DEFAULT 1, + `cost` decimal(10,2) NOT NULL DEFAULT 1.00, + PRIMARY KEY (`id`), + KEY `recipe_FK` (`itemFk`), + KEY `recipe_FK_1` (`elementFk`), + CONSTRAINT `recipe_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE, + CONSTRAINT `recipe_item_FK` FOREIGN KEY (`elementFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Links handmade products with their elements'; + +DROP TABLE IF EXISTS floranet.`element`; \ No newline at end of file diff --git a/db/versions/11075-salmonLilium/00-firstScript.sql b/db/versions/11075-salmonLilium/00-firstScript.sql new file mode 100644 index 000000000..6e487e503 --- /dev/null +++ b/db/versions/11075-salmonLilium/00-firstScript.sql @@ -0,0 +1,5 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS defaultHeight INT UNSIGNED NULL COMMENT 'default height in centimeters'; +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS defaultLength INT UNSIGNED NULL COMMENT 'default length in centimeters'; +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS defaultWidth INT UNSIGNED NULL COMMENT 'default width in centimeters'; +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS defaultWeight INT UNSIGNED NULL COMMENT 'default weight in centimeters'; diff --git a/db/versions/11078-goldenFern/00-firstScript.sql b/db/versions/11078-goldenFern/00-firstScript.sql new file mode 100644 index 000000000..63888a1bb --- /dev/null +++ b/db/versions/11078-goldenFern/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.productionConfig ADD scannablePreviusCodeType enum('qr','barcode') + CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'barcode' NOT NULL; \ No newline at end of file diff --git a/db/versions/11079-goldenFern/00-firstScript.sql b/db/versions/11079-goldenFern/00-firstScript.sql new file mode 100644 index 000000000..14d9ddb5f --- /dev/null +++ b/db/versions/11079-goldenFern/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS expeditionDeadLine TIME NULL +COMMENT 'This field stores the latest time by which expeditions can be generated to be sent today'; \ No newline at end of file diff --git a/db/versions/11080-maroonAnthurium/00-firstScript.sql b/db/versions/11080-maroonAnthurium/00-firstScript.sql new file mode 100644 index 000000000..651cd4c7c --- /dev/null +++ b/db/versions/11080-maroonAnthurium/00-firstScript.sql @@ -0,0 +1,9 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS counterWidth INT UNSIGNED NULL + COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.'; + +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS serviceTypeWidth INT UNSIGNED NULL + COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.'; + +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS portugalPostCodeTrim INT UNSIGNED NULL + COMMENT 'It will trim the last characters of the postal code'; diff --git a/db/versions/11082-goldenCordyline/00-firstScript.sql b/db/versions/11082-goldenCordyline/00-firstScript.sql new file mode 100644 index 000000000..71b98f4a9 --- /dev/null +++ b/db/versions/11082-goldenCordyline/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.country DROP COLUMN country; diff --git a/db/versions/11083-purpleBamboo/00-firstScript.sql b/db/versions/11083-purpleBamboo/00-firstScript.sql new file mode 100644 index 000000000..95e5c30a1 --- /dev/null +++ b/db/versions/11083-purpleBamboo/00-firstScript.sql @@ -0,0 +1,3 @@ + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Ticket','refund','WRITE','ALLOW','ROLE','logistic'); diff --git a/db/versions/11084-whitePalmetto/00-firstScript.sql b/db/versions/11084-whitePalmetto/00-firstScript.sql new file mode 100644 index 000000000..c5f841ea4 --- /dev/null +++ b/db/versions/11084-whitePalmetto/00-firstScript.sql @@ -0,0 +1,9 @@ +CREATE TABLE `vn`.`clientRate` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `dated` date NOT NULL DEFAULT current_timestamp(), + `value` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `clientRate_unique` (`clientFk`,`dated`), + CONSTRAINT `clientRate_client_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; \ No newline at end of file diff --git a/db/versions/11087-aquaDendro/00-firstScript.sql b/db/versions/11087-aquaDendro/00-firstScript.sql new file mode 100644 index 000000000..3490919a9 --- /dev/null +++ b/db/versions/11087-aquaDendro/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.ticket MODIFY COLUMN IF EXISTS isLabeled__ tinyint(1) DEFAULT 0 NOT NULL COMMENT 'refs #7496 deprecated 2024-06-20'; + +ALTER TABLE IF EXISTS vn.forecastedBalance RENAME vn.forecastedBalance__ ; +ALTER TABLE IF EXISTS vn.forecastedBalance__ COMMENT='@deprecated 2024-05-21'; \ No newline at end of file diff --git a/db/versions/11089-blueMastic/00-firstScript.sql b/db/versions/11089-blueMastic/00-firstScript.sql new file mode 100644 index 000000000..a3a92c56c --- /dev/null +++ b/db/versions/11089-blueMastic/00-firstScript.sql @@ -0,0 +1,5 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.expeditionState ADD isScanned tinyint(1) DEFAULT false NOT NULL; diff --git a/db/versions/11090-silverErica/00-firstScript.sql b/db/versions/11090-silverErica/00-firstScript.sql new file mode 100644 index 000000000..ec4959de9 --- /dev/null +++ b/db/versions/11090-silverErica/00-firstScript.sql @@ -0,0 +1,3 @@ +INSERT INTO salix.ACL(model,property,accessType,permission,principalType,principalId) + VALUES('InvoiceIn', 'create', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'create', 'WRITE', 'ALLOW', 'ROLE', 'buyer'); \ No newline at end of file diff --git a/db/versions/11092-azureBirch/00-firstScript.sql b/db/versions/11092-azureBirch/00-firstScript.sql new file mode 100644 index 000000000..12b9d7a20 --- /dev/null +++ b/db/versions/11092-azureBirch/00-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX ticketLog_creationDate_IDX USING BTREE ON vn.ticketLog (creationDate,changedModel,`action`); diff --git a/docker-compose.yml b/docker-compose.yml index ec40311c0..923bb5780 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,62 +4,8 @@ services: image: registry.verdnatura.es/salix-front:${VERSION:?} build: context: front - environment: - - TZ - - NODE_ENV - ports: - - 80 - deploy: - replicas: 2 - placement: - constraints: - - node.role == worker - resources: - limits: - memory: 1G back: image: registry.verdnatura.es/salix-back:${VERSION:?} build: context: . dockerfile: back/Dockerfile - environment: - - TZ - - NODE_ENV - - DEBUG - ports: - - 3000 - configs: - - source: datasources - target: /etc/salix/datasources.json - - source: datasources_local - target: /etc/salix/datasources.local.json - - source: print - target: /etc/salix/print.json - - source: print_local - target: /etc/salix/print.local.json - volumes: - - /mnt/appdata/pdfs:/var/lib/salix/pdfs - - /mnt/appdata/dms:/var/lib/salix/dms - - /mnt/appdata/image:/var/lib/salix/image - - /mnt/appdata/vn-access:/var/lib/salix/vn-access - deploy: - replicas: ${BACK_REPLICAS:?} - placement: - constraints: - - node.role == worker - resources: - limits: - memory: 8G -configs: - datasources: - external: true - name: salix_datasources - datasources_local: - external: true - name: salix-${BRANCH_NAME:?}_datasources - print: - external: true - name: salix_print - print_local: - external: true - name: salix-${BRANCH_NAME:?}_print diff --git a/e2e/paths/02-client/05_add_address.spec.js b/e2e/paths/02-client/05_add_address.spec.js index 0581635d0..4f809a716 100644 --- a/e2e/paths/02-client/05_add_address.spec.js +++ b/e2e/paths/02-client/05_add_address.spec.js @@ -51,7 +51,7 @@ describe('Client Add address path', () => { await page.waitToClick(selectors.clientAddresses.saveButton); const message = await page.waitForSnackbar(); - expect(message.text).toContain('Incoterms is required for a non UEE member'); + expect(message.text).toContain('Incoterms and Customs agent are required for a non UEE member'); }); it(`should receive an error after clicking save button as customsAgent is empty`, async() => { @@ -59,7 +59,7 @@ describe('Client Add address path', () => { await page.waitToClick(selectors.clientAddresses.saveButton); const message = await page.waitForSnackbar(); - expect(message.text).toContain('Customs agent is required for a non UEE member'); + expect(message.text).toContain('Incoterms and Customs agent are required for a non UEE member'); }); it(`should create a new custom agent and then save the address`, async() => { diff --git a/e2e/paths/03-worker/07_pda.spec.js b/e2e/paths/03-worker/07_pda.spec.js deleted file mode 100644 index 2b743823e..000000000 --- a/e2e/paths/03-worker/07_pda.spec.js +++ /dev/null @@ -1,41 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Worker pda path', () => { - let browser; - let page; - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('hr', 'worker'); - await page.accessToSearchResult('employeeNick'); - await page.accessToSection('worker.card.pda'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should check if worker has already a PDA allocated', async() => { - expect(await page.waitToGetProperty(selectors.workerPda.currentPDA, 'value')).toContain('serialNumber1'); - }); - - it('should deallocate the PDA', async() => { - await page.waitToClick(selectors.workerPda.delete); - let message = await page.waitForSnackbar(); - - expect(message.text).toContain('PDA deallocated'); - }); - - it('should allocate a new PDA', async() => { - await page.autocompleteSearch(selectors.workerPda.newPDA, 'serialNumber2'); - await page.waitToClick(selectors.workerPda.submit); - let message = await page.waitForSnackbar(); - - expect(message.text).toContain('PDA allocated'); - }); - - it('should check if a new PDA has been allocated', async() => { - expect(await page.waitToGetProperty(selectors.workerPda.currentPDA, 'value')).toContain('serialNumber2'); - }); -}); diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 4f54ad860..e0f32fc3a 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -225,7 +225,7 @@ describe('Ticket Edit sale path', () => { }); it('should show error trying to delete a ticket with a refund', async() => { - await page.loginAndModule('production', 'ticket'); + await page.loginAndModule('salesPerson', 'ticket'); await page.accessToSearchResult('8'); await page.waitToClick(selectors.ticketDescriptor.moreMenu); await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); diff --git a/front/core/locale/es.yml b/front/core/locale/es.yml index 17e955ff5..7fcb8c16b 100644 --- a/front/core/locale/es.yml +++ b/front/core/locale/es.yml @@ -69,3 +69,4 @@ Send cau: Enviar cau By sending this ticket, all the data related to the error, the section, the user, etc., are already sent.: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc ExplainReason: Explique el motivo por el que no deberia aparecer este fallo You already have the mailAlias: Ya tienes este alias de correo +Error loading ACLs: Error al cargar los ACLs diff --git a/front/core/services/auth.js b/front/core/services/auth.js index 753bc3fba..0cae4bae8 100644 --- a/front/core/services/auth.js +++ b/front/core/services/auth.js @@ -7,16 +7,17 @@ import UserError from 'core/lib/user-error'; * @property {Boolean} loggedIn Whether the user is currently logged */ export default class Auth { - constructor($http, $q, $state, $transitions, $window, vnToken, vnModules, aclService) { + constructor($http, $q, vnApp, $translate, $state, $transitions, $window, vnToken, vnModules) { Object.assign(this, { $http, $q, + vnApp, + $translate, $state, $transitions, $window, vnToken, vnModules, - aclService, loggedIn: false }); } @@ -39,9 +40,26 @@ export default class Auth { }; if (this.vnToken.token) { - return this.loadAcls() - .then(() => true) - .catch(redirectToLogin); + const loadWithRetry = () => { + return this.validateToken() + .then(() => true) + .catch(err => { + switch (err.status) { + case 400: + case 401: + return redirectToLogin(); + default: + return new Promise(resolve => { + setTimeout(() => { + this.vnApp.showMessage(this.$translate.instant('Loading...')); + + resolve(loadWithRetry()); + }, 2000); + }); + } + }); + }; + return loadWithRetry(); } else return redirectToLogin(); }); @@ -87,13 +105,11 @@ export default class Auth { headers: {Authorization: json.data.token} }).then(({data}) => { this.vnToken.set(json.data.token, data.multimediaToken.id, now, json.data.ttl, remember); - this.loadAcls().then(() => { - let continueHash = this.$state.params.continue; - if (continueHash) - this.$window.location = continueHash; - else - this.$state.go('home'); - }); + let continueHash = this.$state.params.continue; + if (continueHash) + this.$window.location = continueHash; + else + this.$state.go('home'); }).catch(() => {}); } @@ -107,24 +123,25 @@ export default class Auth { this.vnToken.unset(); this.loggedIn = false; this.vnModules.reset(); - this.aclService.reset(); + this.vnModules.aclService.reset(); this.$state.go('login'); return promise; } - loadAcls() { - return this.aclService.load() + validateToken() { + return this.$http.get('VnUsers/validateToken') .then(() => { this.loggedIn = true; this.vnModules.reset(); }) .catch(err => { - this.vnToken.unset(); throw err; }); } } -Auth.$inject = ['$http', '$q', '$state', '$transitions', '$window', 'vnToken', 'vnModules', 'aclService']; +Auth.$inject = [ + '$http', '$q', 'vnApp', '$translate', '$state', + '$transitions', '$window', 'vnToken', 'vnModules']; ngModule.service('vnAuth', Auth); diff --git a/front/salix/components/upload-photo/index.js b/front/salix/components/upload-photo/index.js index c9774d037..7779c81e1 100644 --- a/front/salix/components/upload-photo/index.js +++ b/front/salix/components/upload-photo/index.js @@ -164,6 +164,7 @@ export default class UploadPhoto extends Component { const options = { type: 'blob', + size: 'original' }; return this.editor.result(options) .then(blob => this.newPhoto.blob = blob) diff --git a/front/salix/routes.js b/front/salix/routes.js index 8621f83c7..be210b749 100644 --- a/front/salix/routes.js +++ b/front/salix/routes.js @@ -12,7 +12,8 @@ function config($stateProvider, $urlRouterProvider) { template: '', resolve: { config: ['vnConfig', vnConfig => vnConfig.initialize()], - token: ['vnToken', vnToken => vnToken.fetchConfig()] + token: ['vnToken', vnToken => vnToken.fetchConfig()], + acl: ['aclService', aclService => aclService.load()] } }) .state('outLayout', { diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js index 6bdc2c13a..80c58ddc1 100644 --- a/loopback/common/models/application.js +++ b/loopback/common/models/application.js @@ -1,4 +1,3 @@ - module.exports = function(Self) { require('../methods/application/status')(Self); require('../methods/application/post')(Self); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index ca76eae42..740b50bcd 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -61,7 +61,8 @@ "Changed sale discount": "I have changed the following lines discounts from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Created claim": "I have created the claim [{{claimId}}]({{{claimUrl}}}) for the following lines from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Changed sale price": "I have changed the price of [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) from {{oldPrice}}€ ➔ *{{newPrice}}€* of the ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "I have changed the quantity of [{{itemId}} {{concept}}]({{{itemUrl}}}) from {{oldQuantity}} ➔ *{{newQuantity}}* of the ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "I have changed {{changes}} of the ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changes in sales": "the quantity of [{{itemId}} {{concept}}]({{{itemUrl}}}) from {{oldQuantity}} ➔ *{{newQuantity}}*", "Changed sale reserved state": "I have changed the following lines reserved state from the ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Bought units from buy request": "Bought {{quantity}} units of [{{itemId}} {{concept}}]({{{urlItem}}}) for the ticket id [{{ticketId}}]({{{url}}})", "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} ({{clientId}})]({{{url}}}) to *{{credit}} €*", @@ -223,7 +224,13 @@ "printerNotExists": "The printer does not exist", "There are not picking tickets": "There are not picking tickets", "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)", - "This password can only be changed by the user themselves": "This password can only be changed by the user themselves", - "They're not your subordinate": "They're not your subordinate", - "InvoiceIn is already booked": "InvoiceIn is already booked" + "This password can only be changed by the user themselves": "This password can only be changed by the user themselves", + "They're not your subordinate": "They're not your subordinate", + "InvoiceIn is already booked": "InvoiceIn is already booked", + "This workCenter is already assigned to this agency": "This workCenter is already assigned to this agency", + "You can only have one PDA": "You can only have one PDA", + "Incoterms and Customs agent are required for a non UEE member": "Incoterms and Customs agent are required for a non UEE member", + "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated", + "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated" + } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index f1c57455e..714475374 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -124,7 +124,8 @@ "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "He cambiado {{changes}} del ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changes in sales": "la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}*", "State": "Estado", "regular": "normal", "reserved": "reservado", @@ -355,6 +356,14 @@ "No results found": "No se han encontrado resultados", "InvoiceIn is already booked": "La factura recibida está contabilizada", "This workCenter is already assigned to this agency": "Este centro de trabajo ya está asignado a esta agencia", - "Select ticket or client": "Elija un ticket o un client", - "It was not able to create the invoice": "No se pudo crear la factura" -} + "Select ticket or client": "Elija un ticket o un client", + "It was not able to create the invoice": "No se pudo crear la factura", + "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", + "Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE", + "You can not use the same password": "No puedes usar la misma contraseña", + "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", + "You can only have one PDA": "Solo puedes tener un PDA", + "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", + "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", + "Payment method is required": "El método de pago es obligatorio" +} \ No newline at end of file diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 44f5e35d3..1dbd162d8 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -123,8 +123,9 @@ "Added sale to ticket": "J'ai ajouté la ligne suivante au ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", "Changed sale discount": "J'ai changé le rabais des lignes suivantes du ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Created claim": "J'ai créé la réclamation [{{claimId}}]({{{claimUrl}}}) des lignes suivantes du ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Changed sale price": "J'ai changé le prix de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* du ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "J'ai changé la quantité de {{itemId}} {{concept}} de {{oldQuantity}} ➔ {{newQuantity}} du ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale price": " le prix de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* du ticket [{{ticketId}}]({{{ticketUrl}}})",, + "Changed sale quantity": "J'ai changé {{changes}} du ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changes in sales": "la quantité de {{itemId}} {{concept}} de {{oldQuantity}} ➔ {{newQuantity}}", "State": "État", "regular": "normal", "reserved": "réservé", @@ -356,5 +357,7 @@ "InvoiceIn is already booked": "La facture reçue est déjà comptabilisée", "This workCenter is already assigned to this agency": "Ce centre de travail est déjà assigné à cette agence", "Select ticket or client": "Choisissez un ticket ou un client", - "It was not able to create the invoice": "Il n'a pas été possible de créer la facture" -} \ No newline at end of file + "It was not able to create the invoice": "Il n'a pas été possible de créer la facture", + "It has been invoiced but the PDF could not be generated": "La facture a été émise mais le PDF n'a pas pu être généré", + "It has been invoiced but the PDF of refund not be generated": "Il a été facturé mais le PDF de remboursement n'a pas été généré" +} diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index b11eeefc6..95c1fff0a 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -124,7 +124,8 @@ "Changed sale discount": "Desconto da venda alterado no ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Created claim": "Reclamação criada [{{claimId}}]({{{claimUrl}}}) no ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", "Changed sale price": "Preço da venda alterado para [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* no ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "Quantidade da venda alterada para [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* no ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "Quantidade da venda alterada para {{changes}} no ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changes in sales": " [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* ", "State": "Estado", "regular": "normal", "reserved": "reservado", @@ -356,5 +357,7 @@ "InvoiceIn is already booked": "InvoiceIn já está reservado", "This workCenter is already assigned to this agency": "Este centro de trabalho já está atribuído a esta agência", "Select ticket or client": "Selecione um ticket ou cliente", - "It was not able to create the invoice": "Não foi possível criar a fatura" -} \ No newline at end of file + "It was not able to create the invoice": "Não foi possível criar a fatura", + "It has been invoiced but the PDF could not be generated": "Foi faturado, mas o PDF não pôde ser gerado", + "It has been invoiced but the PDF of refund not be generated": "Foi faturado mas não foi gerado o PDF do reembolso" +} diff --git a/loopback/server/boot/isProduction.js b/loopback/server/boot/isProduction.js new file mode 100644 index 000000000..151afa9cb --- /dev/null +++ b/loopback/server/boot/isProduction.js @@ -0,0 +1,3 @@ +module.exports = (localAsProduction = true) => { + return (!process.env.NODE_ENV && localAsProduction) || process.env.NODE_ENV == 'production'; +}; diff --git a/loopback/util/log.js b/loopback/util/log.js index 76e87781d..d2b78ce70 100644 --- a/loopback/util/log.js +++ b/loopback/util/log.js @@ -85,8 +85,12 @@ exports.translateValues = async(instance, changes, options = {}) => { exports.getChanges = (original, changes) => { const oldChanges = {}; const newChanges = {}; + const dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; for (let property in changes) { + if (dateRegex.test(original[property])) + original[property] = new Date(Date.parse(original[property])); + const firstChar = property.substring(0, 1); const isPrivate = firstChar == '$'; if (isPrivate) return; diff --git a/modules/account/back/models/ldap-config.js b/modules/account/back/models/ldap-config.js index 89f0add48..583ce084b 100644 --- a/modules/account/back/models/ldap-config.js +++ b/modules/account/back/models/ldap-config.js @@ -3,9 +3,10 @@ const app = require('vn-loopback/server/server'); const ldap = require('../util/ldapjs-extra'); const crypto = require('crypto'); const nthash = require('smbhash').nthash; +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { - const shouldSync = process.env.NODE_ENV !== 'test'; + const shouldSync = isProduction(); Self.getLinker = async function() { return await Self.findOne({ diff --git a/modules/account/back/models/role-inherit.json b/modules/account/back/models/role-inherit.json index a89f47b77..30d526471 100644 --- a/modules/account/back/models/role-inherit.json +++ b/modules/account/back/models/role-inherit.json @@ -1,6 +1,9 @@ { "name": "RoleInherit", "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "account.roleInherit" diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js index 927510a29..359b4b187 100644 --- a/modules/account/back/models/samba-config.js +++ b/modules/account/back/models/samba-config.js @@ -1,6 +1,7 @@ const ldap = require('../util/ldapjs-extra'); const execFile = require('child_process').execFile; +const isProduction = require('vn-loopback/server/boot/isProduction'); /** * Summary of userAccountControl flags: @@ -12,7 +13,7 @@ const UserAccountControlFlags = { }; module.exports = Self => { - const shouldSync = process.env.NODE_ENV !== 'test'; + const shouldSync = isProduction(); Self.getLinker = async function() { return await Self.findOne({ diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js index b05b2ac15..156caaeec 100644 --- a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js @@ -6,6 +6,7 @@ describe('claimBeginning', () => { const claimManagerId = 72; const activeCtx = { accessToken: {userId: claimManagerId}, + __: value => value }; const ctx = {req: activeCtx}; diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index a206d7f3e..c99e0e2f1 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -88,15 +88,17 @@ module.exports = Self => { const updatedClaim = await claim.updateAttributes(args, myOptions); // When pickup has been changed - if (salesPerson && changedPickup && updatedClaim.pickup) - await notifyPickUp(ctx, salesPerson.id, claim); + if (salesPerson) { + if (changedPickup && updatedClaim.pickup) + await notifyPickUp(ctx, salesPerson.id, claim); - // When claimState has been changed - if (args.claimStateFk) { - const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); - await notifyStateChange(ctx, salesPerson.id, claim, newState.description); - if (newState.code == 'canceled') - await notifyStateChange(ctx, claim.workerFk, claim, newState.description); + // When claimState has been changed + if (args.claimStateFk) { + const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); + await notifyStateChange(ctx, salesPerson.id, claim, newState.description); + if (newState.code == 'canceled') + await notifyStateChange(ctx, claim.workerFk, claim, newState.description); + } } if (tx) await tx.commit(); diff --git a/modules/client/back/methods/client/createAddress.js b/modules/client/back/methods/client/createAddress.js index 8e6db2a22..2709632cb 100644 --- a/modules/client/back/methods/client/createAddress.js +++ b/modules/client/back/methods/client/createAddress.js @@ -92,11 +92,8 @@ module.exports = function(Self) { }, myOptions); const isUeeMember = province.country().isUeeMember; - if (!isUeeMember && !args.incotermsFk) - throw new UserError(`Incoterms is required for a non UEE member`); - - if (!isUeeMember && !args.customsAgentFk) - throw new UserError(`Customs agent is required for a non UEE member`); + if (!isUeeMember && (!args.incotermsFk || !args.customsAgentFk)) + throw new UserError(`Incoterms and Customs agent are required for a non UEE member`); delete args.ctx; // Remove unwanted properties const newAddress = await models.Address.create(args, myOptions); diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js index e2a57272b..23570baf2 100644 --- a/modules/client/back/methods/client/createReceipt.js +++ b/modules/client/back/methods/client/createReceipt.js @@ -95,9 +95,11 @@ module.exports = function(Self) { myOptions ); } else if (accountingType.isAutoConciliated == true) { - const description = `${originalClient.id} : ${originalClient.socialName} - ${accountingType.receiptDescription}`; - const [xdiarioNew] = await Self.rawSql( - `SELECT xdiario_new(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`, + const description = + `${originalClient.id} : ${originalClient.socialName} - ${accountingType.receiptDescription}`; + const [, [xdiarioNew]] = await Self.rawSql( + `CALL xdiario_new(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @xdiarioNew); + SELECT @xdiarioNew ledger;`, [ null, date, @@ -118,7 +120,7 @@ module.exports = function(Self) { ); await Self.rawSql( - `SELECT xdiario_new(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + `CALL xdiario_new(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, @xdiarioNew);`, [ xdiarioNew.ledger, date, diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index 0841ad98c..ae179cf6c 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -50,7 +50,7 @@ describe('Address createAddress', () => { } expect(error).toBeDefined(); - expect(error.message).toEqual('Incoterms is required for a non UEE member'); + expect(error.message).toEqual('Incoterms and Customs agent are required for a non UEE member'); }); it('should throw a non uee member error if no customsAgent is defined', async() => { @@ -81,7 +81,7 @@ describe('Address createAddress', () => { } expect(error).toBeDefined(); - expect(error.message).toEqual('Customs agent is required for a non UEE member'); + expect(error.message).toEqual('Incoterms and Customs agent are required for a non UEE member'); }); it('should create a new address and set as a client default address', async() => { diff --git a/modules/client/back/methods/sms/send.js b/modules/client/back/methods/sms/send.js index 94b2b6c27..2b5674f86 100644 --- a/modules/client/back/methods/sms/send.js +++ b/modules/client/back/methods/sms/send.js @@ -1,5 +1,6 @@ const got = require('got'); const UserError = require('vn-loopback/util/user-error'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethod('send', { @@ -47,7 +48,7 @@ module.exports = Self => { let response; try { - if (process.env.NODE_ENV !== 'production') + if (!isProduction(false)) response = {result: [{status: 'ok'}]}; else { const jsonTest = { diff --git a/modules/client/back/models/XDiario.json b/modules/client/back/models/XDiario.json index be543393d..5c277783a 100644 --- a/modules/client/back/models/XDiario.json +++ b/modules/client/back/models/XDiario.json @@ -76,7 +76,16 @@ }, "enlazadoSage": { "type": "boolean" - } + }, + "enlazado": { + "type": "boolean" + }, + "key": { + "type": "number", + "mysql": { + "columnName": "CLAVE" + } + } }, "relations": { "company": { diff --git a/modules/entry/back/methods/entry/addFromBuy.js b/modules/entry/back/methods/entry/addFromBuy.js index 307c04b97..e5cc427a8 100644 --- a/modules/entry/back/methods/entry/addFromBuy.js +++ b/modules/entry/back/methods/entry/addFromBuy.js @@ -76,7 +76,6 @@ module.exports = Self => { packing: buyUltimate.packing, grouping: buyUltimate.grouping, groupingMode: buyUltimate.groupingMode, - containerFk: buyUltimate.containerFk, comissionValue: buyUltimate.comissionValue, packageValue: buyUltimate.packageValue, location: buyUltimate.location, diff --git a/modules/entry/back/model-config.json b/modules/entry/back/model-config.json index 7b6e23685..dc7fd86be 100644 --- a/modules/entry/back/model-config.json +++ b/modules/entry/back/model-config.json @@ -22,5 +22,8 @@ }, "EntryObservation": { "dataSource": "vn" + }, + "EntryType": { + "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/modules/entry/back/models/buy.json b/modules/entry/back/models/buy.json index 35861fd81..14cafde06 100644 --- a/modules/entry/back/models/buy.json +++ b/modules/entry/back/models/buy.json @@ -63,9 +63,6 @@ "isIgnored": { "type": "boolean" }, - "containerFk": { - "type": "number" - }, "location": { "type": "number" }, diff --git a/modules/entry/back/models/entry-type.json b/modules/entry/back/models/entry-type.json new file mode 100644 index 000000000..989aa3a8a --- /dev/null +++ b/modules/entry/back/models/entry-type.json @@ -0,0 +1,25 @@ +{ + "name": "EntryType", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "entryType" + } + }, + "properties": { + "code": { + "type": "string", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "string" + }, + "isInformal": { + "type": "boolean" + } + } +} \ No newline at end of file diff --git a/modules/entry/back/models/entry.json b/modules/entry/back/models/entry.json index ab451219e..833edf14d 100644 --- a/modules/entry/back/models/entry.json +++ b/modules/entry/back/models/entry.json @@ -35,9 +35,9 @@ }, "isVirtual": { "type": "boolean", - "mysql": { - "columnName": "isRaid" - } + "mysql": { + "columnName": "isRaid" + } }, "isRaid": { "type": "boolean" @@ -53,9 +53,9 @@ }, "observation": { "type": "string", - "mysql": { - "columnName": "evaNotes" - } + "mysql": { + "columnName": "evaNotes" + } }, "loadPriority": { "type": "number" @@ -101,6 +101,11 @@ "type": "belongsTo", "model": "Account", "foreignKey": "observationEditorFk" + }, + "entryType": { + "type": "belongsTo", + "model": "EntryType", + "foreignKey": "typeFk" } } -} +} \ No newline at end of file diff --git a/modules/invoiceIn/back/methods/invoice-in/exchangeRateUpdate.js b/modules/invoiceIn/back/methods/invoice-in/exchangeRateUpdate.js index 3ad06b242..989b1d4a2 100644 --- a/modules/invoiceIn/back/methods/invoice-in/exchangeRateUpdate.js +++ b/modules/invoiceIn/back/methods/invoice-in/exchangeRateUpdate.js @@ -54,6 +54,20 @@ module.exports = Self => { value: rate }); } + const monday = 1; + if (xmlDateWithoutTime.getDay() === monday) { + const saturday = new Date(xmlDateWithoutTime); + saturday.setDate(xmlDateWithoutTime.getDate() - 2); + const sunday = new Date(xmlDateWithoutTime); + sunday.setDate(xmlDateWithoutTime.getDate() - 1); + + for (const date of [saturday, sunday]) { + await models.ReferenceRate.upsertWithWhere( + {currencyFk: currency.id, dated: date}, + {currencyFk: currency.id, dated: date, value: rate} + ); + } + } } } } diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/toUnbook.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/toUnbook.spec.js new file mode 100644 index 000000000..b7d98e307 --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/specs/toUnbook.spec.js @@ -0,0 +1,32 @@ +const models = require('vn-loopback/server/server').models; + +describe('invoiceIn toUnbook()', () => { + it('should check that invoiceIn is unbooked', async() => { + const userId = 1; + const ctx = { + req: { + + accessToken: {userId: userId}, + headers: {origin: 'http://localhost:5000'}, + } + }; + const invoiceInId = 1; + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; + + try { + await models.InvoiceIn.toBook(ctx, invoiceInId, options); + const bookEntry = await models.InvoiceIn.toUnbook(ctx, invoiceInId, options); + const invoiceIn = await models.InvoiceIn.findById(invoiceInId, null, options); + + expect(bookEntry.accountingEntries).toEqual(4); + expect(bookEntry.isLinked).toBeFalsy(); + expect(invoiceIn.isBooked).toEqual(false); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/invoiceIn/back/methods/invoice-in/toBook.js b/modules/invoiceIn/back/methods/invoice-in/toBook.js index 778742911..c3be5f8fc 100644 --- a/modules/invoiceIn/back/methods/invoice-in/toBook.js +++ b/modules/invoiceIn/back/methods/invoice-in/toBook.js @@ -32,7 +32,7 @@ module.exports = Self => { } try { - await Self.rawSql(`CALL vn.invoiceIn_booking(?)`, [id], myOptions); + await Self.rawSql(`CALL vn.invoiceIn_booking(?, NULL)`, [id], myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/invoiceIn/back/methods/invoice-in/toUnbook.js b/modules/invoiceIn/back/methods/invoice-in/toUnbook.js new file mode 100644 index 000000000..a697e9ddc --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/toUnbook.js @@ -0,0 +1,80 @@ +module.exports = Self => { + Self.remoteMethodCtx('toUnbook', { + description: 'To unbook the invoiceIn', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'The invoiceIn id', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: '/:id/toUnbook', + verb: 'POST' + } + }); + + Self.toUnbook = async(ctx, invoiceInId, options) => { + let tx; + const models = Self.app.models; + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + let isLinked; + let accountingEntries; + + let bookEntry = await models.Xdiario.findOne({ + fields: ['ASIEN'], + where: { + and: [ + {key: invoiceInId}, + {enlazado: false}, + {enlazadoSage: false} + ] + } + }, myOptions); + + let asien = bookEntry?.ASIEN; + if (asien) { + accountingEntries = await models.Xdiario.count({ASIEN: asien}, myOptions); + + await models.Xdiario.destroyAll({ASIEN: asien}, myOptions); + await Self.updateAll({id: invoiceInId}, {isBooked: false}, myOptions); + } else { + const linkedBookEntry = await models.Xdiario.findOne({ + fields: ['ASIEN'], + where: { + key: invoiceInId, + and: [{or: [{enlazado: true, enlazadoSage: true}]}] + } + }, myOptions); + + asien = linkedBookEntry?.ASIEN; + isLinked = true; + } + if (tx) await tx.commit(); + + return { + isLinked, + bookEntry: asien, + accountingEntries + }; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js b/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js new file mode 100644 index 000000000..92a1ba8ee --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in/updateInvoiceIn.js @@ -0,0 +1,104 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateInvoiceIn', { + description: 'To update the invoiceIn attributes', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The invoiceIn id', + http: {source: 'path'} + }, { + arg: 'supplierFk', + type: 'number', + required: true + }, { + arg: 'supplierRef', + type: 'any', + }, { + arg: 'issued', + type: 'any', + }, { + arg: 'operated', + type: 'any', + }, { + arg: 'deductibleExpenseFk', + type: 'any', + }, { + arg: 'dmsFk', + type: 'any', + }, { + arg: 'bookEntried', + type: 'any', + }, { + arg: 'booked', + type: 'any', + }, { + arg: 'currencyFk', + type: 'number', + required: true + }, { + arg: 'companyFk', + type: 'any', + }, { + arg: 'withholdingSageFk', + type: 'any', + }, + ], + returns: { + type: 'object', + root: true + }, + http: { + path: '/:id/updateInvoiceIn', + verb: 'PATCH' + } + }); + + Self.updateInvoiceIn = async(ctx, + id, + supplierFk, + supplierRef, + issued, + operated, + deductibleExpenseFk, + dmsFk, + bookEntried, + booked, + currencyFk, + companyFk, + withholdingSageFk, + options + ) => { + let tx; + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const invoiceIn = await Self.findById(id, null, myOptions); + invoiceIn.updateAttributes({supplierFk, + supplierRef, + issued, + operated, + deductibleExpenseFk, + dmsFk, + bookEntried, + booked, + currencyFk, + companyFk, + withholdingSageFk + }, myOptions); + if (tx) await tx.commit(); + return invoiceIn; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceIn/back/models/invoice-in.js b/modules/invoiceIn/back/models/invoice-in.js index 31cdc1abe..1e69c0ef8 100644 --- a/modules/invoiceIn/back/models/invoice-in.js +++ b/modules/invoiceIn/back/models/invoice-in.js @@ -11,6 +11,8 @@ module.exports = Self => { require('../methods/invoice-in/getSerial')(Self); require('../methods/invoice-in/corrective')(Self); require('../methods/invoice-in/exchangeRateUpdate')(Self); + require('../methods/invoice-in/toUnbook')(Self); + require('../methods/invoice-in/updateInvoiceIn')(Self); Self.rewriteDbError(function(err) { if (err.code === 'ER_ROW_IS_REFERENCED_2' && err.sqlMessage.includes('vehicleInvoiceIn')) diff --git a/modules/invoiceIn/front/basic-data/index.html b/modules/invoiceIn/front/basic-data/index.html index a22abbb33..fbb9b05a2 100644 --- a/modules/invoiceIn/front/basic-data/index.html +++ b/modules/invoiceIn/front/basic-data/index.html @@ -1,4 +1,4 @@ - + { Self.remoteMethodCtx('download', { @@ -66,7 +67,7 @@ module.exports = Self => { console.error(err); }); - if (process.env.NODE_ENV == 'test') { + if (!isProduction()) { try { await fs.access(file.path); } catch (error) { diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index eaaef3e26..22787e730 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -1,4 +1,3 @@ - const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); @@ -17,26 +16,27 @@ describe('InvoiceOut transferInvoice()', () => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: activeCtx }); - spyOn(models.InvoiceOut, 'makePdfAndNotify'); }); it('should return the id of the created issued invoice', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; - const args = { - id: '4', - refFk: 'T4444444', - newClientFk: 1, - cplusRectificationTypeFk: 1, - siiTypeInvoiceOutFk: 1, - invoiceCorrectionTypeFk: 1 - }; - ctx.args = args; + const id = 4; + const newClient = 1; + spyOn(models.InvoiceOut, 'makePdfList'); + try { - const {clientFk: oldClient} = await models.InvoiceOut.findById(args.id, {fields: ['clientFk']}); + const {clientFk: oldClient} = await models.InvoiceOut.findById(id, {fields: ['clientFk']}); const invoicesBefore = await models.InvoiceOut.find({}, options); const result = await models.InvoiceOut.transferInvoice( ctx, + id, + 'T4444444', + newClient, + 1, + 1, + 1, + true, options); const invoicesAfter = await models.InvoiceOut.find({}, options); const rectificativeInvoice = invoicesAfter[invoicesAfter.length - 2]; @@ -45,7 +45,7 @@ describe('InvoiceOut transferInvoice()', () => { expect(result).toBeDefined(); expect(invoicesAfter.length - invoicesBefore.length).toEqual(2); expect(rectificativeInvoice.clientFk).toEqual(oldClient); - expect(newInvoice.clientFk).toEqual(args.newClientFk); + expect(newInvoice.clientFk).toEqual(newClient); await tx.rollback(); } catch (e) { @@ -54,22 +54,13 @@ describe('InvoiceOut transferInvoice()', () => { } }); - it('should throw an UserError when it is the same client', async() => { + it('should throw an error when it is the same client', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; - const args = { - id: '1', - refFk: 'T1111111', - newClientFk: 1101, - cplusRectificationTypeFk: 1, - siiTypeInvoiceOutFk: 1, - invoiceCorrectionTypeFk: 1 - }; - ctx.args = args; + spyOn(models.InvoiceOut, 'makePdfList'); + try { - await models.InvoiceOut.transferInvoice( - ctx, - options); + await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1101, 1, 1, 1, true, options); await tx.rollback(); } catch (e) { expect(e.message).toBe(`Select a different client`); @@ -77,26 +68,49 @@ describe('InvoiceOut transferInvoice()', () => { } }); - it('should throw an UserError when it is refund', async() => { + it('should throw an error when it is refund', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; - const args = { - id: '1', - refFk: 'T1111111', - newClientFk: 1102, - cplusRectificationTypeFk: 1, - siiTypeInvoiceOutFk: 1, - invoiceCorrectionTypeFk: 1 - }; - ctx.args = args; + spyOn(models.InvoiceOut, 'makePdfList'); try { - await models.InvoiceOut.transferInvoice( - ctx, - options); + await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1102, 1, 1, 1, true, options); await tx.rollback(); } catch (e) { expect(e.message).toContain(`This ticket is already a refund`); await tx.rollback(); } }); + + it('should throw an error when pdf failed', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + spyOn(models.InvoiceOut, 'makePdfList').and.returnValue(() => { + throw new Error('test'); + }); + + try { + await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1102, 1, 1, 1, true, options); + await tx.rollback(); + } catch (e) { + expect(e.message).toContain(`It has been invoiced but the PDF could not be generated`); + await tx.rollback(); + } + }); + + it('should not generate an invoice', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + spyOn(models.InvoiceOut, 'makePdfList'); + + let response; + try { + response = await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1102, 1, 1, 1, false, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + + expect(response).not.toBeDefined(); + }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index b5eb9bed5..0c86e5810 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -37,13 +37,13 @@ module.exports = Self => { required: true }, { - arg: 'checked', + arg: 'makeInvoice', type: 'boolean', required: true }, ], returns: { - type: 'boolean', + type: 'object', root: true }, http: { @@ -52,11 +52,22 @@ module.exports = Self => { } }); - Self.transferInvoice = async(ctx, options) => { + Self.transferInvoice = async( + ctx, + id, + refFk, + newClientFk, + cplusRectificationTypeFk, + siiTypeInvoiceOutFk, + invoiceCorrectionTypeFk, + makeInvoice, + options + ) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - const {id, refFk, newClientFk, cplusRectificationTypeFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk} = ctx.args; - const checked = ctx.args.checked; + let invoiceId; + let refundId; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -100,15 +111,29 @@ module.exports = Self => { }; const refundTicketIds = refundTickets.map(ticket => ticket.id); - await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); + refundId = await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); - if (!checked) { - const [invoiceId] = await models.Ticket.invoiceTicketsAndPdf(ctx, clonedTicketIds, null, myOptions); - return invoiceId; - } + if (makeInvoice) + invoiceId = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, null, myOptions); + + tx && await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } + + if (tx && makeInvoice) { + try { + await models.InvoiceOut.makePdfList(ctx, invoiceId); + } catch (e) { + throw new UserError('It has been invoiced but the PDF could not be generated'); + } + try { + await models.InvoiceOut.makePdfList(ctx, refundId); + } catch (e) { + throw new UserError('It has been invoiced but the PDF of refund not be generated'); + } + } + return invoiceId; }; }; diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index e4fcc1a69..b0e05b626 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -1,6 +1,7 @@ const print = require('vn-print'); const path = require('path'); const UserError = require('vn-loopback/util/user-error'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { require('../methods/invoiceOut/filter')(Self); @@ -59,7 +60,7 @@ module.exports = Self => { hasPdf: true }, options); - if (process.env.NODE_ENV !== 'test') { + if (isProduction()) { await print.storage.write(buffer, { type: 'invoice', path: pdfFile.path, diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 0d7fb32dd..8ea4507ec 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -158,7 +158,7 @@ class Controller extends Section { cplusRectificationTypeFk: this.cplusRectificationType, siiTypeInvoiceOutFk: this.siiTypeInvoiceOut, invoiceCorrectionTypeFk: this.invoiceCorrectionType, - checked: this.checked + makeInvoice: this.checked }; this.$http.get(`Clients/${this.clientId}`).then(response => { diff --git a/modules/invoiceOut/front/index/manual/index.html b/modules/invoiceOut/front/index/manual/index.html index 5872911e4..3b991618d 100644 --- a/modules/invoiceOut/front/index/manual/index.html +++ b/modules/invoiceOut/front/index/manual/index.html @@ -27,7 +27,7 @@ { accessType: 'READ', accepts: [{ arg: 'barcode', - type: 'number', + type: 'string', required: true, description: 'barcode' }], @@ -18,7 +18,7 @@ module.exports = Self => { } }); - Self.toItem = async(barcode, options) => { + Self.toItem = async (barcode, options) => { const myOptions = {}; if (typeof options == 'object') diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 5e5148595..728b5f33e 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -64,7 +64,7 @@ describe('item getBalance()', () => { const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options); expect(firstItemBalance[9].claimFk).toEqual(null); - expect(secondItemBalance[4].claimFk).toEqual(2); + expect(secondItemBalance[7].claimFk).toEqual(2); await tx.rollback(); } catch (e) { diff --git a/modules/item/back/models/expense.json b/modules/item/back/models/expense.json index 468063602..e661cbc66 100644 --- a/modules/item/back/models/expense.json +++ b/modules/item/back/models/expense.json @@ -9,7 +9,7 @@ "properties": { "id": { "id": true, - "type": "number", + "type": "string", "description": "Identifier" }, "name": { diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 9d48dcbfb..10cff3e04 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -155,6 +155,9 @@ "minQuantity": { "type": "number", "description": "Min quantity" + }, + "photoMotivation": { + "type": "string" } }, "relations": { diff --git a/modules/mdb/back/methods/mdbVersion/upload.js b/modules/mdb/back/methods/mdbVersion/upload.js index 58fc46abb..64de72679 100644 --- a/modules/mdb/back/methods/mdbVersion/upload.js +++ b/modules/mdb/back/methods/mdbVersion/upload.js @@ -1,6 +1,7 @@ const fs = require('fs-extra'); const path = require('path'); const UserError = require('vn-loopback/util/user-error'); +const isProduction = require('vn-loopback/server/boot/isProduction'); module.exports = Self => { Self.remoteMethodCtx('upload', { @@ -111,7 +112,7 @@ module.exports = Self => { const destinationFile = path.join( accessContainer.client.root, accessContainer.name, appName, `${toVersion}.7z`); - if (process.env.NODE_ENV == 'test') + if (!isProduction()) await fs.unlink(srcFile); else { await fs.move(srcFile, destinationFile, { diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index bdafd14e2..c3da7f08b 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => { const result = await models.SalesMonitor.salesFilter(ctx, filter, options); const firstRow = result[0]; - expect(result.length).toEqual(12); + expect(result.length).toEqual(15); expect(firstRow.alertLevel).not.toEqual(0); await tx.rollback(); diff --git a/modules/route/back/locale/routesMonitor/en.yml b/modules/route/back/locale/routesMonitor/en.yml index 8908ee636..c28c5cb4d 100644 --- a/modules/route/back/locale/routesMonitor/en.yml +++ b/modules/route/back/locale/routesMonitor/en.yml @@ -13,7 +13,6 @@ columns: m3: m3 priority: priority etd: etd - expeditionTruckFk: truck m3boxes: m3 boxes bufferFk: buffer - isPickingAllowed: is picking allowed \ No newline at end of file + isPickingAllowed: is picking allowed diff --git a/modules/route/back/locale/routesMonitor/es.yml b/modules/route/back/locale/routesMonitor/es.yml index 9ded8983d..a8e807626 100644 --- a/modules/route/back/locale/routesMonitor/es.yml +++ b/modules/route/back/locale/routesMonitor/es.yml @@ -13,7 +13,6 @@ columns: m3: m3 priority: prioridad etd: etd - expeditionTruckFk: camión m3boxes: m3 cajas bufferFk: buffer - isPickingAllowed: está permitido recoger \ No newline at end of file + isPickingAllowed: está permitido recoger diff --git a/modules/route/back/methods/roadmap/clone.js b/modules/route/back/methods/roadmap/clone.js index 456ed823d..5f1ab9229 100644 --- a/modules/route/back/methods/roadmap/clone.js +++ b/modules/route/back/methods/roadmap/clone.js @@ -37,17 +37,12 @@ module.exports = Self => { fields: [ 'id', 'name', - 'tractorPlate', - 'trailerPlate', - 'phone', 'supplierFk', - 'etd', - 'observations', - 'price'], + 'etd'], include: [{ - relation: 'expeditionTruck', + relation: 'roadmapStop', scope: { - fields: ['roadmapFk', 'warehouseFk', 'eta', 'description'] + fields: ['roadmapFk', 'addressFk', 'eta', 'description'] } }] @@ -62,12 +57,12 @@ module.exports = Self => { const clone = await models.Roadmap.create(roadmap, options); - const expeditionTrucks = roadmap.expeditionTruck(); - expeditionTrucks.map(expeditionTruck => { - expeditionTruck.roadmapFk = clone.id; - return expeditionTruck; + const roadmapStops = roadmap.roadmapStop(); + roadmapStops.map(roadmapStop => { + roadmapStop.roadmapFk = clone.id; + return roadmapStop; }); - await models.ExpeditionTruck.create(expeditionTrucks, options); + await models.RoadmapStop.create(roadmapStops, options); } await tx.commit(); diff --git a/modules/route/back/model-config.json b/modules/route/back/model-config.json index 6cf8da986..ccae87bd9 100644 --- a/modules/route/back/model-config.json +++ b/modules/route/back/model-config.json @@ -8,7 +8,10 @@ "DeliveryPoint": { "dataSource": "vn" }, - "ExpeditionTruck": { + "RoadmapAddress": { + "dataSource": "vn" + }, + "RoadmapStop": { "dataSource": "vn" }, "Roadmap": { diff --git a/modules/route/back/models/roadmap.json b/modules/route/back/models/roadmap.json index 2f6bb8c02..01572d718 100644 --- a/modules/route/back/models/roadmap.json +++ b/modules/route/back/models/roadmap.json @@ -54,9 +54,9 @@ "model": "Supplier", "foreignKey": "supplierFk" }, - "expeditionTruck": { + "roadmapStop": { "type": "hasMany", - "model": "ExpeditionTruck", + "model": "RoadmapStop", "foreignKey": "roadmapFk" } } diff --git a/modules/route/back/models/roadmapAddress.json b/modules/route/back/models/roadmapAddress.json new file mode 100644 index 000000000..0241ce0d8 --- /dev/null +++ b/modules/route/back/models/roadmapAddress.json @@ -0,0 +1,26 @@ +{ + "name": "RoadmapAddress", + "base": "VnModel", + "options": { + "mysql": { + "table": "roadmapAddress" + } + }, + "properties": { + "addressFk": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "isActive": { + "type": "number" + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + } +} diff --git a/modules/route/back/models/expedition-truck.json b/modules/route/back/models/roadmapStop.json similarity index 78% rename from modules/route/back/models/expedition-truck.json rename to modules/route/back/models/roadmapStop.json index 8edc7347f..74b02cd7a 100644 --- a/modules/route/back/models/expedition-truck.json +++ b/modules/route/back/models/roadmapStop.json @@ -1,9 +1,9 @@ { - "name": "ExpeditionTruck", + "name": "RoadmapStop", "base": "VnModel", "options": { "mysql": { - "table": "expeditionTruck" + "table": "roadmapStop" } }, "properties": { @@ -15,7 +15,7 @@ "roadmapFk": { "type": "number" }, - "warehouseFk": { + "addressFk": { "type": "number" }, "eta": { @@ -34,10 +34,10 @@ "model": "Roadmap", "foreignKey": "roadmapFk" }, - "warehouse": { + "address": { "type": "belongsTo", - "model": "Warehouse", - "foreignKey": "warehouseFk" + "model": "Address", + "foreignKey": "addressFk" } } } diff --git a/modules/route/back/models/routesMonitor.json b/modules/route/back/models/routesMonitor.json index 122026336..a14680b5c 100644 --- a/modules/route/back/models/routesMonitor.json +++ b/modules/route/back/models/routesMonitor.json @@ -48,9 +48,6 @@ "priority": { "type": "number" }, - "expeditionTruckFk": { - "type": "number" - }, "m3boxes": { "type": "number" }, diff --git a/modules/route/front/roadmap/stops/index.html b/modules/route/front/roadmap/stops/index.html index b69492a21..82f30c326 100644 --- a/modules/route/front/roadmap/stops/index.html +++ b/modules/route/front/roadmap/stops/index.html @@ -1,22 +1,22 @@ - + + ng-model="roadmapStop.eta"> diff --git a/modules/route/front/roadmap/summary/index.html b/modules/route/front/roadmap/summary/index.html index 9fab0bf87..abf5ff90a 100644 --- a/modules/route/front/roadmap/summary/index.html +++ b/modules/route/front/roadmap/summary/index.html @@ -49,7 +49,7 @@ vn-bind="+" vn-tooltip="Add stop" icon="add_circle" - vn-click-stop="addExpeditionTruck.show()"> + vn-click-stop="addRoadmapStop.show()"> @@ -61,9 +61,9 @@ - - {{expeditionTruck.warehouse.name}} - {{expeditionTruck.eta | date:'dd/MM/yyyy HH:mm'}} + + {{roadmapStop.warehouse.name}} + {{roadmapStop.eta | date:'dd/MM/yyyy HH:mm'}} @@ -75,14 +75,14 @@ + ng-model="$ctrl.roadmapStop.eta"> diff --git a/modules/route/front/roadmap/summary/index.js b/modules/route/front/roadmap/summary/index.js index 041b43ce3..46abe5ca2 100644 --- a/modules/route/front/roadmap/summary/index.js +++ b/modules/route/front/roadmap/summary/index.js @@ -20,7 +20,7 @@ class Controller extends Component { include: [ {relation: 'supplier'}, {relation: 'worker'}, - {relation: 'expeditionTruck', + {relation: 'roadmapStop', scope: { include: [ {relation: 'warehouse'} @@ -36,19 +36,19 @@ class Controller extends Component { const eta = new Date(this.roadmap.etd); eta.setDate(eta.getDate() + 1); - this.expeditionTruck = {eta: eta}; + this.roadmapStop = {eta: eta}; } onAddAccept() { try { const data = { roadmapFk: this.roadmap.id, - warehouseFk: this.expeditionTruck.warehouseFk, - eta: this.expeditionTruck.eta, - description: this.expeditionTruck.description + warehouseFk: this.roadmapStop.warehouseFk, + eta: this.roadmapStop.eta, + description: this.roadmapStop.description }; - this.$http.post(`ExpeditionTrucks`, data) + this.$http.post(`RoadmapStops`, data) .then(() => { this.loadData(); this.vnApp.showSuccess(this.$t('Data saved!')); diff --git a/modules/shelving/back/model-config.json b/modules/shelving/back/model-config.json index 89a0832b0..6f3ffb5ea 100644 --- a/modules/shelving/back/model-config.json +++ b/modules/shelving/back/model-config.json @@ -11,6 +11,12 @@ "Sector": { "dataSource": "vn" }, + "SectorCollection": { + "dataSource": "vn" + }, + "SectorCollectionSaleGroup": { + "dataSource": "vn" + }, "Train": { "dataSource": "vn" } diff --git a/modules/shelving/back/models/sectorCollection.json b/modules/shelving/back/models/sectorCollection.json new file mode 100644 index 000000000..bf2cc7985 --- /dev/null +++ b/modules/shelving/back/models/sectorCollection.json @@ -0,0 +1,24 @@ +{ + "name": "SectorCollection", + "base": "VnModel", + "options": { + "mysql": { + "table": "sectorCollection" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "created": { + "type": "date" + }, + "userFk": { + "type": "number" + }, + "sectorFk": { + "type": "number" + } + } +} diff --git a/modules/shelving/back/models/sectorCollectionSaleGroup.json b/modules/shelving/back/models/sectorCollectionSaleGroup.json new file mode 100644 index 000000000..421bdc885 --- /dev/null +++ b/modules/shelving/back/models/sectorCollectionSaleGroup.json @@ -0,0 +1,30 @@ +{ + "name": "SectorCollectionSaleGroup", + "base": "VnModel", + "options": { + "mysql": { + "table": "sectorCollectionSaleGroup" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "created": { + "type": "date" + } + }, + "relations": { + "sectorCollection": { + "type": "belongsTo", + "model": "SectorCollection", + "foreignKey": "sectorCollectionFk" + }, + "saleGroup": { + "type": "belongsTo", + "model": "SaleGroup", + "foreignKey": "saleGroupFk" + } + } +} diff --git a/modules/supplier/back/methods/supplier/getItemsPackaging.js b/modules/supplier/back/methods/supplier/getItemsPackaging.js index c06195a55..8a27c89c4 100644 --- a/modules/supplier/back/methods/supplier/getItemsPackaging.js +++ b/modules/supplier/back/methods/supplier/getItemsPackaging.js @@ -33,7 +33,7 @@ module.exports = Self => { JOIN vn.item i ON i.id = b.itemFk WHERE e.id = ? AND e.supplierFk = ? GROUP BY i.id - ) SELECT i.id, i.name, et.quantity, SUM(b.quantity) quantityTotal, et.printedStickers + ) SELECT i.id, i.name, et.quantity, SUM(b.quantity) quantityTotal, et.printedStickers, ic.url FROM vn.buy b JOIN vn.item i ON i.id = b.itemFk JOIN vn.entry e ON e.id = b.entryFk @@ -41,6 +41,7 @@ module.exports = Self => { JOIN vn.buyConfig bc ON bc.monthsAgo JOIN vn.travel t ON t.id = e.travelFk LEFT JOIN entryTmp et ON et.id = i.id + JOIN hedera.imageConfig ic WHERE e.supplierFk = ? AND i.family IN ('EMB', 'CONT') AND b.created > (util.VN_CURDATE() - INTERVAL bc.monthsAgo MONTH) diff --git a/modules/ticket/back/methods/expedition-state/addExpeditionState.js b/modules/ticket/back/methods/expedition-state/addExpeditionState.js index 8eab1a838..80d74ee92 100644 --- a/modules/ticket/back/methods/expedition-state/addExpeditionState.js +++ b/modules/ticket/back/methods/expedition-state/addExpeditionState.js @@ -44,11 +44,13 @@ module.exports = Self => { const typeFk = expeditionStateType.id; expeditionId = expedition.expeditionFk; + const isScannedExpedition = expedition.isScanned ?? false; await models.ExpeditionState.create({ expeditionFk: expedition.expeditionFk, typeFk, userFk: userId, + isScanned: isScannedExpedition, }, myOptions); } diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 77c40d8a0..fa1079fbe 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -135,6 +135,7 @@ module.exports = Self => { const now = Date.vnNew(); const ticket = await models.Ticket.findById(ticketId, null, myOptions); + if (!ctx.args) ctx.args = {}; ctx.args.clientId = ticket.clientFk; ctx.args.shipped = now; ctx.args.landed = now; diff --git a/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js b/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js index 3d37221c4..3d39ea278 100644 --- a/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js +++ b/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js @@ -2,10 +2,12 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('ticket setDelivered()', () => { - const userId = 50; + const userId = 49; const activeCtx = { accessToken: {userId: userId}, + __: value => value }; + const ctx = {req: activeCtx}; beforeAll(async() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ @@ -19,8 +21,6 @@ describe('ticket setDelivered()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 49}}}; - const originalTicketOne = await models.Ticket.findById(8, null, options); const originalTicketTwo = await models.Ticket.findById(10, null, options); diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 826de6e12..8dc7a633c 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -10,8 +10,8 @@ module.exports = Self => { http: {source: 'path'} }, { - arg: 'itemId', - type: 'number', + arg: 'barcode', + type: 'any', required: true }, { @@ -29,7 +29,7 @@ module.exports = Self => { } }); - Self.addSale = async(ctx, id, itemId, quantity, options) => { + Self.addSale = async(ctx, id, barcode, quantity, options) => { const $t = ctx.req.__; // $translate const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; @@ -46,7 +46,9 @@ module.exports = Self => { try { await models.Ticket.isEditableOrThrow(ctx, id, myOptions); + const itemId = await models.ItemBarcode.toItem(barcode, myOptions); const item = await models.Item.findById(itemId, null, myOptions); + const ticket = await models.Ticket.findById(id, { include: { relation: 'client', diff --git a/modules/ticket/back/methods/ticket/addSaleByCode.js b/modules/ticket/back/methods/ticket/addSaleByCode.js deleted file mode 100644 index ca3d2cb07..000000000 --- a/modules/ticket/back/methods/ticket/addSaleByCode.js +++ /dev/null @@ -1,56 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); -module.exports = Self => { - Self.remoteMethodCtx('addSaleByCode', { - description: 'Add a collection', - accessType: 'WRITE', - accepts: [ - { - arg: 'barcode', - type: 'string', - required: true - }, { - arg: 'quantity', - type: 'number', - required: true - }, { - arg: 'ticketFk', - type: 'number', - required: true - }, { - arg: 'warehouseFk', - type: 'number', - required: true - }, - - ], - http: { - path: `/addSaleByCode`, - verb: 'POST' - }, - }); - - Self.addSaleByCode = async(ctx, barcode, quantity, ticketFk, warehouseFk, options) => { - const myOptions = {userId: ctx.req.accessToken.userId}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [barcode, warehouseFk], myOptions); - if (!item?.available) throw new UserError('We do not have availability for the selected item'); - - await Self.rawSql('CALL vn.collection_addItem(?, ?, ?)', [item.id, quantity, ticketFk], myOptions); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/ticket/back/methods/ticket/closeAll.js b/modules/ticket/back/methods/ticket/closeAll.js index d35bd1e3e..35b9b1e37 100644 --- a/modules/ticket/back/methods/ticket/closeAll.js +++ b/modules/ticket/back/methods/ticket/closeAll.js @@ -138,12 +138,13 @@ module.exports = Self => { JOIN alertLevel al ON al.id = ts.alertLevel JOIN agencyMode am ON am.id = t.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - JOIN zone z ON z.id = t.zoneFk + LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id SET t.routeFk = NULL WHERE DATE(t.shipped) BETWEEN ? - INTERVAL 2 DAY AND util.dayEnd(?) - AND al.code NOT IN('DELIVERED','PACKED') - AND t.routeFk - AND z.name LIKE '%MADRID%'`, [toDate, toDate], {userId: ctx.req.accessToken.userId}); + AND al.code NOT IN ('DELIVERED', 'PACKED') + AND NOT t.packages + AND tob.id IS NULL + AND t.routeFk`, [toDate, toDate], {userId: ctx.req.accessToken.userId}); return { message: 'Success' diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 8c59dc3b0..fba39f18f 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -13,8 +13,6 @@ module.exports = async function(ctx, Self, tickets, reqArgs = {}) { const failedtickets = []; for (const ticket of tickets) { try { - await Self.rawSql(`CALL util.debugAdd('invoicingTicket', ?)`, [ticket.id], {userId}); - await Self.app.models.InvoiceOut.getSerial(ticket.clientFk, ticket.companyFk, ticket.addressFk, 'M'); await Self.rawSql( `CALL vn.ticket_closeByTicket(?)`, diff --git a/modules/ticket/back/methods/ticket/isEditableOrThrow.js b/modules/ticket/back/methods/ticket/isEditableOrThrow.js index 16cff84f1..555063093 100644 --- a/modules/ticket/back/methods/ticket/isEditableOrThrow.js +++ b/modules/ticket/back/methods/ticket/isEditableOrThrow.js @@ -8,18 +8,13 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const state = await models.TicketState.findOne({ - where: {ticketFk: id} - }, myOptions); - + const state = await models.TicketState.findOne({where: {ticketFk: id}}, myOptions); const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + const isProductionReviewer = await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*'); const canEditWeeklyTicket = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'canEditWeekly', 'WRITE'); const alertLevel = state ? state.alertLevel : null; const ticket = await models.Ticket.findById(id, { - fields: ['clientFk'], - include: { - relation: 'client' - } + fields: ['clientFk'], include: {relation: 'client'} }, myOptions); const isLocked = await models.Ticket.isLocked(id, myOptions); @@ -29,10 +24,24 @@ module.exports = Self => { const isNormalClient = ticket && ticket.client().typeFk == 'normal'; const isEditable = !(alertLevelGreaterThanZero && isNormalClient); + const ticketCollection = await models.TicketCollection.findOne({ + include: {relation: 'collection'}, where: {ticketFk: id} + }, myOptions); + let isOwner = ticketCollection?.collection()?.workerFk === ctx.req.accessToken.userId; + + if (!isOwner) { + const saleGroup = await models.SaleGroup.findOne({fields: ['id'], where: {ticketFk: id}}, myOptions); + const sectorCollectionSaleGroup = saleGroup && await models.SectorCollectionSaleGroup.findOne({ + include: {relation: 'sectorCollection'}, where: {saleGroupFk: saleGroup.id} + }, myOptions); + + isOwner = sectorCollectionSaleGroup?.sectorCollection()?.userFk === ctx.req.accessToken.userId; + } + if (!ticket) throw new ForbiddenError(`The ticket doesn't exist.`); - if (!isEditable && !isRoleAdvanced) + if (!isEditable && !isRoleAdvanced && !isProductionReviewer && !isOwner) throw new ForbiddenError(`This ticket is not editable.`); if (isLocked && !isWeekly) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 490b05320..b5c662089 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -140,14 +140,7 @@ module.exports = Self => { await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); - const deliveryState = await models.State.findOne({ - where: {code: 'DELIVERED'} - }, myOptions); - - await models.Ticket.state(ctx, { - ticketFk: ticketId, - stateFk: deliveryState.id - }, myOptions); + await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions); if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { await models.Ticket.saveCmr(ctx, [ticketId], myOptions); diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 9a9fd9056..2afdf44ac 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -71,7 +71,10 @@ module.exports = Self => { // Check for existing purchase requests const hasPurchaseRequests = await models.TicketRequest.count({ ticketFk: id, - isOk: true + or: [ + {isOk: true}, + {isOk: null} + ] }, myOptions); if (hasPurchaseRequests) diff --git a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js deleted file mode 100644 index b97139178..000000000 --- a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js +++ /dev/null @@ -1,39 +0,0 @@ -const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); - -describe('Ticket addSaleByCode()', () => { - const quantity = 3; - const ticketFk = 13; - const warehouseFk = 1; - beforeAll(async() => { - activeCtx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - __: value => value - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - - it('should add a new sale', async() => { - const tx = await models.Ticket.beginTransaction({}); - - try { - const options = {transaction: tx}; - const code = '1111111111'; - - const salesBefore = await models.Sale.find(null, options); - await models.Ticket.addSaleByCode(activeCtx, code, quantity, ticketFk, warehouseFk, options); - const salesAfter = await models.Sale.find(null, options); - - expect(salesAfter.length).toEqual(salesBefore.length + 1); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index e495a41f5..8008acfaf 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toEqual(7); + expect(result.length).toEqual(10); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js index e5c06b6dd..7dc1c8ed2 100644 --- a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js +++ b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js @@ -42,7 +42,7 @@ describe('sale priceDifference()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 1106}}}; + const ctx = {req: {accessToken: {userId: 1105}}}; ctx.args = { id: 1, landed: Date.vnNew(), @@ -84,7 +84,7 @@ describe('sale priceDifference()', () => { const {items} = await models.Ticket.priceDifference(ctx, options); - expect(items[0].movable).toEqual(410); + expect(items[0].movable).toEqual(386); expect(items[1].movable).toEqual(1810); await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index 520a9e403..cb2a21d91 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -49,7 +49,7 @@ describe('ticket setDeleted()', () => { ctx.req.__ = value => { return value; }; - const ticketId = 23; + const ticketId = 24; const [sectorCollectionBefore] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows FROM vn.sectorCollection`, [], options); @@ -87,7 +87,7 @@ describe('ticket setDeleted()', () => { const [ticketCollectionOld] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows FROM vn.ticketCollection`, [], options); - const ticketId = 23; + const ticketId = 34; await models.Ticket.setDeleted(ctx, ticketId, options); diff --git a/modules/ticket/back/methods/ticket/specs/state.spec.js b/modules/ticket/back/methods/ticket/specs/state.spec.js index 947e72b79..d908aa2ef 100644 --- a/modules/ticket/back/methods/ticket/specs/state.spec.js +++ b/modules/ticket/back/methods/ticket/specs/state.spec.js @@ -7,6 +7,7 @@ describe('ticket state()', () => { const productionId = 49; const activeCtx = { accessToken: {userId: 9}, + __: value => value }; const ctx = {req: activeCtx}; const now = Date.vnNew(); @@ -88,7 +89,8 @@ describe('ticket state()', () => { const ticket = await models.Ticket.create(sampleTicket, options); activeCtx.accessToken.userId = productionId; - const params = {ticketFk: ticket.id, stateFk: 3}; + const stateOk = await models.State.findOne({where: {code: 'OK'}}, options); + const params = {ticketFk: ticket.id, stateFk: stateOk.id}; const ticketTracking = await models.Ticket.state(ctx, params, options); @@ -112,16 +114,68 @@ describe('ticket state()', () => { const options = {transaction: tx}; const ticket = await models.Ticket.create(sampleTicket, options); - const ctx = {req: {accessToken: {userId: 18}}}; + activeCtx.accessToken.userId = salesPersonId; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); - const params = {ticketFk: ticket.id, stateFk: assignedState.id, userFk: 1}; - const res = await models.Ticket.state(ctx, params, options); + const paramsAssigned = {ticketFk: ticket.id, stateFk: assignedState.id, userFk: 1}; + const resAssigned = await models.Ticket.state(ctx, paramsAssigned, options); - expect(res.ticketFk).toBe(params.ticketFk); - expect(res.stateFk).toBe(params.stateFk); - expect(res.userFk).toBe(params.userFk); - expect(res.userFk).toBe(1); - expect(res.id).toBeDefined(); + expect(resAssigned.ticketFk).toBe(paramsAssigned.ticketFk); + expect(resAssigned.stateFk).toBe(paramsAssigned.stateFk); + expect(resAssigned.userFk).toBe(paramsAssigned.userFk); + expect(resAssigned.userFk).toBe(1); + expect(resAssigned.id).toBeDefined(); + + activeCtx.accessToken.userId = productionId; + const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options); + const paramsPacked = {ticketFk: ticket.id, stateFk: packedState.id, userFk: salesPersonId}; + const resPacked = await models.Ticket.state(ctx, paramsPacked, options); + + expect(resPacked.stateFk).toBe(paramsPacked.stateFk); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('Should equalize the quantities of quantity and originalQuantity' + + ' if they are different', async() => { + const tx = await models.TicketTracking.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const ticket = await models.Ticket.create(sampleTicket, options); + activeCtx.accessToken.userId = salesPersonId; + + const sampleSale = { + ticketFk: ticket.id, + itemFk: 1, + concept: 'Test', + quantity: 10, + originalQuantity: 6 + }; + await models.Sale.create(sampleSale, options); + const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); + const paramsAssigned = {ticketFk: ticket.id, stateFk: assignedState.id, userFk: 1}; + const resAssigned = await models.Ticket.state(ctx, paramsAssigned, options); + + expect(resAssigned.ticketFk).toBe(paramsAssigned.ticketFk); + expect(resAssigned.stateFk).toBe(paramsAssigned.stateFk); + expect(resAssigned.userFk).toBe(paramsAssigned.userFk); + expect(resAssigned.userFk).toBe(1); + expect(resAssigned.id).toBeDefined(); + + activeCtx.accessToken.userId = productionId; + const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options); + const paramsPacked = {ticketFk: ticket.id, stateFk: packedState.id, userFk: salesPersonId}; + const resPacked = await models.Ticket.state(ctx, paramsPacked, options); + + const sale = await models.Sale.findOne({where: {ticketFk: ticket.id}}, options); + + expect(resPacked.stateFk).toBe(paramsPacked.stateFk); + expect(sale.quantity).toBe(sale.originalQuantity); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/state.js b/modules/ticket/back/methods/ticket/state.js index fea9475f8..9b0b862f2 100644 --- a/modules/ticket/back/methods/ticket/state.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -64,7 +64,63 @@ module.exports = Self => { if ((ticketState && !oldStateAllowed) || !newStateAllowed) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); - await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions); + const ticket = await models.Ticket.findById(params.ticketFk, { + include: [{ + relation: 'client', + scope: { + fields: ['salesPersonFk'] + } + }], + fields: ['id', 'clientFk'] + }, myOptions); + + const salesPersonFk = ticket.client().salesPersonFk; + if (salesPersonFk) { + const sales = await Self.rawSql(` + SELECT DISTINCT s.id, + s.itemFk, + s.concept, + s.originalQuantity AS oldQuantity, + s.quantity AS newQuantity + FROM vn.sale s + JOIN vn.saleTracking st ON st.saleFk = s.id + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.ticketState ts ON ts.ticketFk = t.id + JOIN vn.state s2 ON s2.id = ts.stateFk + WHERE s.ticketFk = ? + AND st.isChecked + AND s.originalQuantity IS NOT NULL + AND s.originalQuantity <> s.quantity + AND s2.\`order\` < (SELECT \`order\` FROM vn.state WHERE code = 'CHECKED') + ORDER BY st.created DESC + `, [params.ticketFk], myOptions); + + let changes = ''; + const url = await models.Url.getUrl(); + const $t = ctx.req.__; + for (let sale of sales) { + changes += `\r\n-` + $t('Changes in sales', { + itemId: sale.itemFk, + concept: sale.concept, + oldQuantity: sale.oldQuantity, + newQuantity: sale.newQuantity, + itemUrl: `${url}item/${sale.itemFk}/summary` + }); + const currentSale = await models.Sale.findById(sale.id, null, myOptions); + await currentSale.updateAttributes({ + originalQuantity: currentSale.quantity + }, myOptions); + } + + const message = $t('Changed sale quantity', { + ticketId: ticket.id, + changes: changes, + ticketUrl: `${url}ticket/${ticket.id}/sale` + }); + await models.Chat.sendCheckingPresence(ctx, salesPersonFk, message, myOptions); + } + await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticket.id, params.code], myOptions); const ticketTracking = await models.TicketTracking.findOne({ where: {ticketFk: params.ticketFk}, diff --git a/modules/ticket/back/models/expedition-state.json b/modules/ticket/back/models/expedition-state.json index eda0f79fd..159a9275e 100644 --- a/modules/ticket/back/models/expedition-state.json +++ b/modules/ticket/back/models/expedition-state.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "expeditionState" + "table": "expeditionState" } }, "properties": { @@ -23,13 +23,16 @@ }, "userFk": { "type": "number" + }, + "isScanned": { + "type": "boolean" } }, "relations": { - "expeditionStateType": { - "type": "belongsTo", - "model": "ExpeditionStateType", - "foreignKey": "typeFk" - } + "expeditionStateType": { + "type": "belongsTo", + "model": "ExpeditionStateType", + "foreignKey": "typeFk" + } } -} +} \ No newline at end of file diff --git a/modules/ticket/back/models/expeditionPallet.json b/modules/ticket/back/models/expeditionPallet.json index cab3af6ec..64b3092ae 100644 --- a/modules/ticket/back/models/expeditionPallet.json +++ b/modules/ticket/back/models/expeditionPallet.json @@ -23,9 +23,9 @@ } }, "relations": { - "expeditionTruck": { + "roadmapStop": { "type": "belongsTo", - "model": "ExpeditionTruck", + "model": "RoadmapStop", "foreignKey": "truckFk" } } diff --git a/modules/ticket/back/models/saleGroup.json b/modules/ticket/back/models/saleGroup.json index d5cf82cb5..aa78b4167 100644 --- a/modules/ticket/back/models/saleGroup.json +++ b/modules/ticket/back/models/saleGroup.json @@ -14,6 +14,9 @@ }, "parkingFk": { "type": "number" + }, + "ticketFk": { + "type": "number" } }, "relations": { diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js index d078dc8e2..1aa40802b 100644 --- a/modules/ticket/back/models/specs/sale.spec.js +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -1,361 +1,318 @@ /* eslint max-len: ["error", { "code": 150 }]*/ - -const models = require('vn-loopback/server/server').models; +const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('sale model ', () => { - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - function getActiveCtx(userId) { - return { - active: { - accessToken: {userId}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - } - }; + const developerId = 9; + const buyerId = 35; + const employeeId = 1; + const productionId = 49; + const salesPersonId = 18; + const reviewerId = 130; + + const barcode = '4444444444'; + const ticketCollectionProd = 34; + const ticketCollectionSalesPerson = 35; + const previaTicketSalesPerson = 36; + const previaTicketProd = 37; + const notEditableError = 'This ticket is not editable.'; + + const ctx = getCtx(developerId); + let tx; + let opts; + + function getCtx(userId, active = false) { + const accessToken = {userId}; + const headers = {origin: 'localhost:5000'}; + if (!active) return {req: {accessToken, headers, __: () => {}}}; + return {active: {accessToken, http: {req: {headers}}}}; } + beforeEach(async() => { + tx = await models.Sale.beginTransaction({}); + opts = {transaction: tx}; + }); + + afterEach(async() => await tx.rollback()); + describe('quantity field ', () => { it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { const saleId = 17; - const buyerId = 35; - const ctx = { - req: { - accessToken: {userId: buyerId}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - const tx = await models.Sale.beginTransaction({}); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const ctx = getCtx(buyerId); + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(buyerId, true)); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT 100 as available;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - try { - const options = {transaction: tx}; + const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + expect(isRoleAdvanced).toEqual(true); - expect(isRoleAdvanced).toEqual(true); + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + expect(originalLine.quantity).toEqual(30); - expect(originalLine.quantity).toEqual(30); + const newQuantity = originalLine.quantity + 1; + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); - const newQuantity = originalLine.quantity + 1; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(modifiedLine.quantity).toEqual(newQuantity); }); it('should update the quantity of a given sale current line', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(developerId, true)); - const tx = await models.Sale.beginTransaction({}); const saleId = 25; const newQuantity = 4; - try { - const options = {transaction: tx}; + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + expect(originalLine.quantity).toEqual(20); - expect(originalLine.quantity).toEqual(20); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(modifiedLine.quantity).toEqual(newQuantity); }); it('should throw an error if the quantity is negative and it is not a refund ticket', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); const saleId = 17; const newQuantity = -10; - const tx = await models.Sale.beginTransaction({}); - - let error; try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); } catch (e) { - await tx.rollback(); - error = e; + expect(e).toEqual(new Error('You can only add negative amounts in refund tickets')); } - - expect(error).toEqual(new Error('You can only add negative amounts in refund tickets')); }); it('should update a negative quantity when is a ticket refund', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(developerId, true)); - const tx = await models.Sale.beginTransaction({}); const saleId = 32; const newQuantity = -10; - try { - const options = {transaction: tx}; + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(modifiedLine.quantity).toEqual(newQuantity); }); it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = minQuantity - 1; - let error; try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT 100 as available;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); } catch (e) { - await tx.rollback(); - error = e; + expect(e).toEqual(new Error('The amount cannot be less than the minimum')); } - - expect(error).toEqual(new Error('The amount cannot be less than the minimum')); }); it('should change quantity if has minimum quantity and new quantity is equal than item available', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = minQuantity - 1; - try { - const options = {transaction: tx}; + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, opts); + }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); }); describe('newPrice', () => { it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = 31; - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, opts); + }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); }); it('should increase quantity when the new price is lower than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = 31; - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, opts); + }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); }); it('should throw error when increase quantity and the new price is higher than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = 31; - let error; try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 100000 as price;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); } catch (e) { - await tx.rollback(); - error = e; + expect(e).toEqual(new Error('The price of the item changed')); } - - expect(error).toEqual(new Error('The price of the item changed')); }); }); }); + + describe('add a sale from a collection or previa ticket', () => { + it('if is allocated to them and alert level higher than 0 as Production role', async() => { + const ctx = getCtx(productionId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(productionId, true)); + + const beforeSalesCollection = await models.Sale.count({ticketFk: ticketCollectionProd}, opts); + await models.Ticket.addSale(ctx, ticketCollectionProd, barcode, 20, opts); + const afterSalesCollection = await models.Sale.count({ticketFk: ticketCollectionProd}, opts); + + expect(afterSalesCollection).toEqual(beforeSalesCollection + 1); + + const beforeSalesPrevia = await models.Sale.count({ticketFk: previaTicketProd}, opts); + await models.Ticket.addSale(ctx, previaTicketProd, barcode, 20, opts); + const afterSalesPrevia = await models.Sale.count({ticketFk: previaTicketProd}, opts); + + expect(afterSalesPrevia).toEqual(beforeSalesPrevia + 1); + }); + + it('should throw an error if is not allocated to them and alert level higher than 0 as Production role', async() => { + const ctx = getCtx(productionId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(productionId, true)); + + try { + await models.Ticket.addSale(ctx, ticketCollectionSalesPerson, barcode, 20, opts); + } catch ({message}) { + expect(message).toEqual(notEditableError); + } + + try { + await models.Ticket.addSale(ctx, previaTicketSalesPerson, barcode, 20, opts); + } catch ({message}) { + expect(message).toEqual(notEditableError); + } + }); + + it('if is allocated to them and alert level higher than 0 as salesPerson role', async() => { + const ctx = getCtx(salesPersonId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(salesPersonId, true)); + + const beforeSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + await models.Ticket.addSale(ctx, ticketCollectionSalesPerson, barcode, 20, opts); + const afterSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + + expect(afterSalesCollection).toEqual(beforeSalesCollection + 1); + + const beforeSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + await models.Ticket.addSale(ctx, previaTicketSalesPerson, barcode, 20, opts); + const afterSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + + expect(afterSalesPrevia).toEqual(beforeSalesPrevia + 1); + }); + + it('should throw an error if is not allocated to them and alert level higher than 0 as salesPerson role', async() => { + const ctx = getCtx(salesPersonId); + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(salesPersonId, true)); + + try { + await models.Ticket.addSale(ctx, ticketCollectionProd, barcode, 20, opts); + } catch ({message}) { + expect(message).toEqual(notEditableError); + } + }); + + it('if is a reviewer', async() => { + const ctx = getCtx(reviewerId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(reviewerId, true)); + + const beforeSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + await models.Ticket.addSale(ctx, ticketCollectionSalesPerson, barcode, 20, opts); + const afterSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + + expect(afterSalesCollection).toEqual(beforeSalesCollection + 1); + + const beforeSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + await models.Ticket.addSale(ctx, previaTicketSalesPerson, barcode, 20, opts); + const afterSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + + expect(afterSalesPrevia).toEqual(beforeSalesPrevia + 1); + }); + }); }); diff --git a/modules/ticket/back/models/ticket-log.json b/modules/ticket/back/models/ticket-log.json index 32b4afd13..d75589f11 100644 --- a/modules/ticket/back/models/ticket-log.json +++ b/modules/ticket/back/models/ticket-log.json @@ -8,7 +8,8 @@ }, "properties": { "id": { - "type": "string" + "type": "number", + "id": true }, "originFk": { "type": "number" diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index 0ae2ce3b4..5582dde5c 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -46,6 +46,5 @@ module.exports = function(Self) { require('../methods/ticket/invoiceTicketsAndPdf')(Self); require('../methods/ticket/docuwareDownload')(Self); require('../methods/ticket/myLastModified')(Self); - require('../methods/ticket/addSaleByCode')(Self); require('../methods/ticket/clone')(Self); }; diff --git a/modules/ticket/front/card/index.js b/modules/ticket/front/card/index.js index fa4ad4e39..34ab109c5 100644 --- a/modules/ticket/front/card/index.js +++ b/modules/ticket/front/card/index.js @@ -1,5 +1,6 @@ import ngModule from '../module'; import ModuleCard from 'salix/components/module-card'; +import UserError from 'core/lib/user-error'; class Controller extends ModuleCard { reload() { @@ -59,6 +60,10 @@ class Controller extends ModuleCard { ], }; + if (!this.$params.id) { + this.$state.go('ticket.index'); + throw new UserError(`You must select a ticket`); + } return this.$http.get(`Tickets/${this.$params.id}`, {filter}) .then(res => this.onData(res.data)); } diff --git a/modules/ticket/front/descriptor-menu/index.html b/modules/ticket/front/descriptor-menu/index.html index cb7eeb8ee..3583b1202 100644 --- a/modules/ticket/front/descriptor-menu/index.html +++ b/modules/ticket/front/descriptor-menu/index.html @@ -152,7 +152,7 @@ diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index 52cac141c..32f245454 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -37,18 +37,19 @@ class Controller extends Section { }); const filter = { - fields: ['originFk', 'creationDate', 'newInstance'], + fields: ['id', 'originFk', 'creationDate', 'newInstance'], where: { originFk: value, newInstance: {like: '%"isDeleted":true%'} }, - order: 'creationDate DESC' + order: 'creationDate DESC', + limit: 1 }; - this.$http.get(`TicketLogs/findOne`, {filter}) + this.$http.get(`TicketLogs`, {filter}) .then(res => { - if (res && res.data) { + if (res && res.data && res.data.length) { const now = Date.vnNew(); - const maxDate = new Date(res.data.creationDate); + const maxDate = new Date(res.data[0].creationDate); maxDate.setHours(maxDate.getHours() + 1); if (now <= maxDate) return this.canRestoreTicket = true; diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml index 748ba210f..2f448c034 100644 --- a/modules/ticket/front/locale/es.yml +++ b/modules/ticket/front/locale/es.yml @@ -64,6 +64,7 @@ You are going to delete this ticket: Vas a eliminar este ticket Ticket deleted. You can undo this action within the first hour: Ticket eliminado. Puedes deshacer esta acción durante la primera hora Search ticket by id or alias: Buscar tickets por identificador o alias ticket: ticket +You must select a ticket: Debes seleccionar un ticket #sections List: Listado diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index 1cd5560a4..7ff8d89e3 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -476,7 +476,7 @@ class Controller extends Section { */ addSale(sale) { const data = { - itemId: sale.itemFk, + barcode: sale.itemFk, quantity: sale.quantity }; const query = `tickets/${this.ticket.id}/addSale`; diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index fb1c925d4..8200d6b89 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -659,7 +659,7 @@ describe('Ticket', () => { jest.spyOn(controller, 'resetChanges').mockReturnThis(); const newSale = {itemFk: 4, quantity: 10}; - const expectedParams = {itemId: 4, quantity: 10}; + const expectedParams = {barcode: 4, quantity: 10}; const expectedResult = { id: 30, quantity: 10, diff --git a/modules/travel/back/methods/travel/cloneWithEntries.js b/modules/travel/back/methods/travel/cloneWithEntries.js index e5eb0b06c..12afad6e2 100644 --- a/modules/travel/back/methods/travel/cloneWithEntries.js +++ b/modules/travel/back/methods/travel/cloneWithEntries.js @@ -26,18 +26,17 @@ module.exports = Self => { Self.cloneWithEntries = async(ctx, id, options) => { const conn = Self.dataSource.connector; + let tx; const myOptions = {}; - let tx = options?.transaction; + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - const travel = await Self.findById(id, { fields: [ 'id', @@ -89,6 +88,8 @@ module.exports = Self => { 'ref' ] }, myOptions); + + if (tx) await tx.commit(); return newTravel.id; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js b/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js index 950da7bb1..8b3638db9 100644 --- a/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js +++ b/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js @@ -7,19 +7,22 @@ describe('Travel cloneWithEntries()', () => { const ctx = {req: {accessToken: {userId: currentUserId}}}; let newTravelId; it(`should clone the travel and the containing entries`, async() => { - const tx = await models.Travel.beginTransaction({ - }); + const tx = await models.Travel.beginTransaction({}); const warehouseThree = 3; const agencyModeOne = 1; + let travelRemoved; + try { const options = {transaction: tx}; + newTravelId = await models.Travel.cloneWithEntries(ctx, travelId, options); const travelEntries = await models.Entry.find({ where: { travelFk: newTravelId } }, options); - const newTravel = await models.Travel.findById(travelId); + const newTravel = await models.Travel.findById(travelId, null, options); + travelRemoved = await models.Travel.findById(newTravelId); expect(newTravelId).not.toEqual(travelId); expect(newTravel.ref).toEqual('fifth travel'); @@ -27,14 +30,9 @@ describe('Travel cloneWithEntries()', () => { expect(newTravel.warehouseOutFk).toEqual(warehouseThree); expect(newTravel.agencyModeFk).toEqual(agencyModeOne); expect(travelEntries.length).toBeGreaterThan(0); - await models.Entry.destroyAll({ - travelFk: newTravelId - }, options); - await models.Travel.destroyById(newTravelId, options); - await tx.rollback(); - const travelRemoved = await models.Travel.findById(newTravelId, options); - expect(travelRemoved).toBeNull(); + + await tx.rollback(); } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/worker/back/methods/worker/getAvailablePda.js b/modules/worker/back/methods/worker/getAvailablePda.js new file mode 100644 index 000000000..65641a9e6 --- /dev/null +++ b/modules/worker/back/methods/worker/getAvailablePda.js @@ -0,0 +1,23 @@ +module.exports = Self => { + Self.remoteMethod('getAvailablePda', { + description: 'returns devices without user', + accessType: 'READ', + accepts: [], + returns: { + type: 'array', + root: true + }, + http: { + path: `/getAvailablePda`, + verb: 'GET' + } + }); + Self.getAvailablePda = async() => { + return Self.app.models.DeviceProduction.rawSql( + `SELECT d.* + FROM deviceProduction d + LEFT JOIN deviceProductionUser du ON du.deviceProductionFk = d.id + WHERE du.deviceProductionFk IS NULL` + ); + }; +}; diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 5316daf01..ba9dc3853 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -5,108 +5,80 @@ module.exports = Self => { Self.remoteMethodCtx('new', { description: 'Creates a new worker and returns the id', accessType: 'WRITE', - accepts: [ - { - arg: 'fi', - type: 'string', - description: `The worker fi`, - required: true, - }, - { - arg: 'name', - type: 'string', - description: `The user name`, - required: true, - }, - { - arg: 'firstName', - type: 'string', - description: `The worker firstname`, - required: true, - }, - { - arg: 'lastNames', - type: 'string', - description: `The worker lastnames`, - required: true, - }, - { - arg: 'email', - type: 'string', - description: `The worker email`, - required: true, - }, - { - arg: 'street', - type: 'string', - description: `The worker address`, - required: true, - }, - { - arg: 'city', - type: 'string', - description: `The worker city`, - required: true, - }, - { - arg: 'provinceFk', - type: 'number', - description: `The worker province`, - required: true, - }, - { - arg: 'companyFk', - type: 'number', - description: `The worker company`, - required: true, - }, - { - arg: 'postcode', - type: 'string', - description: `The worker postcode`, - required: true, - }, - { - arg: 'phone', - type: 'string', - description: `The worker phone`, - required: true, - }, - { - arg: 'code', - type: 'string', - description: `The worker code`, - required: true, - }, - { - arg: 'bossFk', - type: 'number', - description: `The worker boss`, - required: true, - }, - { - arg: 'birth', - type: 'date', - description: `The worker birth`, - required: true, - }, - { - arg: 'payMethodFk', - type: 'number', - description: `The client payMethod`, - required: true, - }, - { - arg: 'iban', - type: 'string', - description: `The client iban`, - }, - { - arg: 'bankEntityFk', - type: 'number', - description: `The client bank entity`, - } - ], + accepts: [{ + arg: 'fi', + type: 'string', + description: `The worker fi`, + }, { + arg: 'name', + type: 'string', + description: `The user name`, + }, { + arg: 'firstName', + type: 'string', + description: `The worker firstname`, + }, { + arg: 'lastNames', + type: 'string', + description: `The worker lastnames`, + }, { + arg: 'email', + type: 'string', + description: `The worker email`, + required: true, + }, { + arg: 'street', + type: 'string', + description: `The worker address`, + }, { + arg: 'city', + type: 'string', + description: `The worker city`, + }, { + arg: 'provinceFk', + type: 'number', + description: `The worker province`, + }, { + arg: 'companyFk', + type: 'number', + description: `The worker company`, + }, { + arg: 'postcode', + type: 'string', + description: `The worker postcode`, + }, { + arg: 'phone', + type: 'string', + description: `The worker phone`, + }, { + arg: 'code', + type: 'string', + description: `The worker code`, + }, { + arg: 'bossFk', + type: 'number', + description: `The worker boss`, + required: true, + }, { + arg: 'birth', + type: 'date', + description: `The worker birth`, + }, { + arg: 'payMethodFk', + type: 'number', + description: `The client payMethod`, + }, { + arg: 'iban', + type: 'string', + description: `The client iban`, + }, { + arg: 'bankEntityFk', + type: 'number', + description: `The client bank entity`, + }, { + arg: 'isFreelance', + type: 'boolean', + }], returns: { type: 'number', root: true, @@ -117,11 +89,30 @@ module.exports = Self => { }, }); - Self.new = async(ctx, options) => { + Self.new = async( + ctx, + fi, + name, + firstName, + lastNames, + email, + street, + city, + provinceFk, + companyFk, + postcode, + phone, + code, + bossFk, + birth, + payMethodFk, + iban, + bankEntityFk, + isFreelance, + options + ) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - const args = ctx.args; - let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -132,132 +123,105 @@ module.exports = Self => { } let client; - + let user; try { - client = await models.Client.findOne( - { - where: {fi: args.fi}, - }, - myOptions - ); + client = await models.Client.findOne({where: {fi}}, myOptions); + const nickname = firstName.concat(' ', lastNames); + const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']}); - if (!client) { - const nickname = args.firstName.concat(' ', args.lastNames); - const workerConfig = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']}); - const [randomPassword] = await models.Worker.rawSql( - 'SELECT account.passwordGenerate() as password;' - ); + if (!isFreelance && !payMethodFk) throw new UserError('Payment method is required'); - const user = await models.VnUser.create( - { - name: args.name, - nickname, - password: randomPassword.password, - email: args.email, - roleFk: workerConfig.roleFk, - }, - myOptions - ); + if (isFreelance || !client) { + const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;'); + const freelancer = isFreelance && await models.VnRole.findOne({fields: ['id'], where: {name: 'freelancer'}}); - await models.Account.create( - { - id: user.id, - }, - myOptions - ); + user = await models.VnUser.create({ + name, + nickname, + password, + email, + roleFk: freelancer ? freelancer.id : roleFk, + }, myOptions); - const payMethod = await models.PayMethod.findById(args.payMethodFk, {fields: ['isIbanRequiredForClients']}); - if (payMethod.isIbanRequiredForClients && !args.iban) - throw new UserError(`That payment method requires an IBAN`); + await models.Account.create({ + id: user.id + }, myOptions); + } else if (client) user = await models.VnUser.findById(client.id, null, myOptions); - await models.Worker.rawSql( - 'CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', + if (!client && !isFreelance) { + const payMethod = await models.PayMethod.findById(payMethodFk, {fields: ['isIbanRequiredForClients']}); + if (payMethod.isIbanRequiredForClients && !iban) throw new UserError('That payment method requires an IBAN'); + + await models.Worker.rawSql('CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [ - args.firstName, - args.lastNames, - args.fi, - args.street, - args.postcode, - args.city, - args.provinceFk, - args.companyFk, - args.phone, - args.email, + firstName, + lastNames, + fi, + street, + postcode, + city, + provinceFk, + companyFk, + phone, + email, user.id, ], - myOptions - ); + myOptions); - const address = await models.Address.create( - { - clientFk: user.id, - street: args.street, - city: args.city, - provinceFk: args.provinceFk, - postalCode: args.postcode, - mobile: args.phone, - nickname: nickname, - isDefaultAddress: true, - }, - myOptions - ); + const address = await models.Address.create({ + clientFk: user.id, + street: street, + city: city, + provinceFk: provinceFk, + postalCode: postcode, + mobile: phone, + nickname: nickname, + isDefaultAddress: true, + }, myOptions); - client = await models.Client.findById( - user.id, - {fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']}, - myOptions - ); + client = await models.Client.findById(user.id, { + fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi'] + }, myOptions); - await client.updateAttributes( - { - payMethod: args.payMethod, - iban: args.iban, - bankEntityFk: args.bankEntityFk, - defaultAddressFk: address.id, - businessTypeFk: workerConfig.businessTypeFk, - }, - myOptions - ); + await client.updateAttributes({ + payMethod: payMethodFk, + iban, + bankEntityFk, + defaultAddressFk: address.id, + businessTypeFk, + }, myOptions); } - const user = await models.VnUser.findById(client.id, null, myOptions); - await user.updateAttribute('email', args.email, myOptions); + await user.updateAttribute('email', email, myOptions); await models.Worker.create({ - id: client.id, - code: args.code, - firstName: args.firstName, - lastName: args.lastNames, - bossFk: args.bossFk, - fi: args.fi, - birth: args.birth, + id: user.id, + firstName, + lastName: lastNames, + code, + bossFk, + fi, + birth, }, myOptions); if (tx) await tx.commit(); - } catch (error) { + } catch (e) { if (tx) await tx.rollback(); - const code = error.code; - const message = error.sqlMessage; + const code = e.code; + const message = e.sqlMessage; - if (error.message && error.message.includes(`Email already exists`)) - throw new UserError(`This personal mail already exists`); + if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`); - if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) - throw new UserError(`This worker code already exists`); + if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`); - if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) - throw new UserError(`This worker already exists`); + if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`); - throw error; + throw e; } - await models.VnUser.resetPassword({ - email: args.email, - emailTemplate: 'worker-welcome', - id: client.id - }); + await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: user.id}); - return {id: client.id}; + return {id: user.id}; }; }; diff --git a/modules/worker/back/methods/worker/specs/getAvailablePda.spec.js b/modules/worker/back/methods/worker/specs/getAvailablePda.spec.js new file mode 100644 index 000000000..c7051f0b4 --- /dev/null +++ b/modules/worker/back/methods/worker/specs/getAvailablePda.spec.js @@ -0,0 +1,13 @@ +const models = require('vn-loopback/server/server').models; + +describe('worker getAvailablePda()', () => { + it('should return a Pda that has no user assigned', async() => { + const [{id}] = await models.Worker.getAvailablePda(); + + const deviceProductionUser = await models.DeviceProductionUser.findOne({ + where: {deviceProductionFk: id} + }); + + expect(!deviceProductionUser).toBeTruthy(); + }); +}); diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 66959e0a7..5a5649154 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -1,189 +1,114 @@ -const models = require('vn-loopback/server/server').models; +const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Worker new', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - + const developerId = 9; const employeeId = 1; - const defaultWorker = { - fi: '78457139E', - name: 'defaulterworker', - firstName: 'DEFAULT', - lastNames: 'WORKER', - email: 'defaultWorker@mydomain.com', - street: 'S/ DEFAULTWORKERSTREET', - city: 'defaultWorkerCity', - provinceFk: 1, - companyFk: 442, - postcode: '46680', - phone: '123456789', - code: 'DWW', - bossFk: 9, - birth: '2022-12-11T23:00:00.000Z', - payMethodFk: 1, - roleFk: 1 - }; + const bruceWayneId = 1101; + const accessToken = {accessToken: {userId: developerId}}; + const ctx = {req: accessToken}; + let tx; + let opts; - const req = {accessToken: {userId: 9}}; - - it('should return error if personal mail already exists', async() => { - const user = await models.VnUser.findById(employeeId, {fields: ['email']}); - - const tx = await models.Worker.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {email: user.email}), - req - }; - - await models.Worker.new(ctx, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error.message).toEqual('This personal mail already exists'); + beforeAll(async() => { + const activeCtx = {accessToken, http: {req: {headers: {origin: 'http://localhost'}}}}; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: activeCtx}); }); - it('should return error if worker code already exists', async() => { - const worker = await models.Worker.findById(employeeId, {fields: ['code']}); - - const tx = await models.Worker.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {code: worker.code}), - req - }; - - await models.Worker.new(ctx, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error.message).toEqual('This worker code already exists'); - }); - - it('should return error if worker already exists', async() => { - const worker = await models.Client.findById(employeeId, {fields: ['fi']}); - - const tx = await models.Worker.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {fi: worker.fi}), - req - }; - await models.Worker.new(ctx, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error.message).toEqual('This worker already exists'); - }); - - it('should return error if payMethod require iban', async() => { - const payMethodIbanRequired = await models.PayMethod.findOne({ - where: { - isIbanRequiredForClients: true - }, - fields: ['id'] + describe('should return error', () => { + beforeEach(async() => { + tx = await models.Worker.beginTransaction({}); + opts = {transaction: tx}; }); - const tx = await models.Worker.beginTransaction({}); + afterEach(async() => await tx.rollback()); - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}), - req - }; - await models.Worker.new(ctx, options); + it('if personal mail already exists', async() => { + const user = await models.VnUser.findById(employeeId, {fields: ['email']}); + try { + await createWorker(ctx, opts, {email: user.email}); + } catch (e) { + expect(e.message).toEqual('This personal mail already exists'); + } + }); - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } + it('if worker code already exists', async() => { + const worker = await models.Worker.findById(employeeId, {fields: ['code']}); + try { + await createWorker(ctx, opts, {code: worker.code}); + } catch (e) { + expect(e.message).toEqual('This worker code already exists'); + } + }); - expect(error.message).toEqual('That payment method requires an IBAN'); + it('if worker already exists', async() => { + const worker = await models.Client.findById(employeeId, {fields: ['fi']}); + try { + await createWorker(ctx, opts, {fi: worker.fi}); + } catch (e) { + expect(e.message).toEqual('This worker already exists'); + } + }); + + it('if payMethod require iban', async() => { + const payMethodIbanRequired = await models.PayMethod.findOne({ + fields: ['id'], where: {isIbanRequiredForClients: true} + }); + + try { + await createWorker(ctx, opts, {payMethodFk: payMethodIbanRequired.id}); + } catch (e) { + expect(e.message).toEqual('That payment method requires an IBAN'); + } + }); }); it('should create a new worker', async() => { let newWorker; try { - newWorker = await models.Worker.new({args: defaultWorker, req}); + newWorker = await createWorker(ctx); + + expect(newWorker.id).toBeDefined(); } finally { await removeWorker(newWorker.id); } - - expect(newWorker.id).toBeDefined(); }); it('should create a new client', async() => { let newWorker; - let client; try { - newWorker = await models.Worker.new({args: defaultWorker, req}); - client = await models.Client.findById(newWorker.id); + newWorker = await createWorker(ctx); + let client = await models.Client.findById(newWorker.id); + + expect(client).toBeDefined(); } finally { await removeWorker(newWorker.id); } - - expect(client).toBeDefined(); }); it('should create a new worker in client', async() => { - const bruceWayneId = 1101; const client = await models.Client.findById(bruceWayneId, {fields: ['fi', 'email']}); - - const newWorkerData = { - args: Object.assign( - {}, - defaultWorker, - { - fi: client.fi, - email: client.email - }), - req - }; let newWorker; try { - newWorker = await models.Worker.new(newWorkerData); + newWorker = await createWorker(ctx, undefined, {fi: client.fi, email: client.email}); + + expect(newWorker.id).toEqual(bruceWayneId); } finally { await models.Worker.destroyById(newWorker.id); } + }); - expect(newWorker.id).toEqual(bruceWayneId); + it('should create a new external worker', async() => { + let newWorker; + try { + newWorker = await createWorker(ctx, undefined, {isFreelance: true}); + const client = await models.Client.findById(newWorker.id); + + expect(newWorker.id).toBeDefined(); + expect(client).toBeNull(); + } finally { + await removeWorker(newWorker.id); + } }); }); @@ -194,3 +119,28 @@ async function removeWorker(id) { await models.Client.destroyById(id); await models.VnUser.destroyById(id); } + +async function createWorker(ctx, opts = undefined, params = {}) { + return models.Worker.new( + ctx, + params.fi ?? '78457139E', + params.name ?? 'defaulterworker', + params.firstName ?? 'DEFAULT', + params.lastNames ?? 'WORKER', + params.email ?? 'defaultWorker@mydomain.com', + params.street ?? 'S/ DEFAULTWORKERSTREET', + params.city ?? 'defaultWorkerCity', + params.provinceFk ?? 1, + params.companyFk ?? 442, + params.postcode ?? '46680', + params.phone ?? '123456789', + params.code ?? 'DWW', + params.bossFk ?? 9, + params.birth ?? '2022-12-11T23:00:00.000Z', + params.payMethodFk ?? 1, + undefined, + undefined, + params.isFreelance ?? false, + opts + ); +} diff --git a/modules/worker/back/models/device-production-user.js b/modules/worker/back/models/device-production-user.js new file mode 100644 index 000000000..8eead58e0 --- /dev/null +++ b/modules/worker/back/models/device-production-user.js @@ -0,0 +1,11 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`This PDA is already assigned to another user`); + + if (err.code === 'ER_SIGNAL_EXCEPTION' && err.sqlMessage === 'You can only have one active PDA') + return new UserError(err.sqlMessage); + return err; + }); +}; diff --git a/modules/worker/back/models/device-production-user.json b/modules/worker/back/models/device-production-user.json index 35a90fb50..a024cc94c 100644 --- a/modules/worker/back/models/device-production-user.json +++ b/modules/worker/back/models/device-production-user.json @@ -14,6 +14,10 @@ } }, "properties": { + "id": { + "type": "number", + "id": true + }, "deviceProductionFk": { "type": "number", "id": true @@ -21,6 +25,9 @@ "userFk": { "type": "number" }, + "simSerialNumber": { + "type": "string" + }, "created": { "type": "date" } @@ -28,7 +35,7 @@ "relations": { "deviceProduction": { "type": "belongsTo", - "model": "DeviceProduction", + "model": "DeviceProduction", "foreignKey": "deviceProductionFk" }, "user": { @@ -36,5 +43,10 @@ "model": "User", "foreignKey": "userFk" } + }, + "scope": { + "include":{ + "relation": "deviceProduction" + } } } diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index d46f3d934..70e20af5b 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -20,7 +20,7 @@ module.exports = Self => { const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, - status: 'sent' + status: {neq: 'error'} } }); diff --git a/modules/worker/back/models/specs/locker.spec.js b/modules/worker/back/models/specs/locker.spec.js index 32abb830e..96fca2405 100644 --- a/modules/worker/back/models/specs/locker.spec.js +++ b/modules/worker/back/models/specs/locker.spec.js @@ -6,8 +6,9 @@ describe('locker model ', () => { const hrId = 37; const jessicaJonesId = 1110; const bruceBannerId = 1109; - const lockerMaleId = 1; - const lockerFemaleId = 147; + const lockerMaleId = 3; + const lockerFemaleId = 5; + const lockerNewFemaleId = 6; let ctx; let options; let tx; @@ -46,11 +47,13 @@ describe('locker model ', () => { }); it('should change a locker', async() => { - const locker = await models.Locker.findById(148, null, options); - await locker.updateAttributes({workerFk: jessicaJonesId}, options); const oldLocker = await models.Locker.findById(lockerFemaleId, null, options); + const locker = await models.Locker.findById(lockerNewFemaleId, null, options); + await locker.updateAttributes({workerFk: jessicaJonesId}, options); + const oldNowLocker = await models.Locker.findById(lockerFemaleId, null, options); + expect(oldLocker.workerFk).toEqual(jessicaJonesId); expect(locker.workerFk).toEqual(jessicaJonesId); - expect(oldLocker.workerFk).toEqual(null); + expect(oldNowLocker.workerFk).toEqual(null); }); }); diff --git a/modules/worker/back/models/worker.js b/modules/worker/back/models/worker.js index 076f2eaab..0b0e043f2 100644 --- a/modules/worker/back/models/worker.js +++ b/modules/worker/back/models/worker.js @@ -20,6 +20,7 @@ module.exports = Self => { require('../methods/worker/search')(Self); require('../methods/worker/isAuthorized')(Self); require('../methods/worker/setPassword')(Self); + require('../methods/worker/getAvailablePda')(Self); Self.validateAsync('fi', tinIsValid, { message: 'Invalid TIN' diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index adfe2c58e..4796c6373 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -25,43 +25,59 @@ "required": true }, "phone": { - "type" : "string" + "type": "string" }, "bossFk": { - "type" : "number" + "type": "number" }, "maritalStatus": { - "type" : "string" + "type": "string" }, "originCountryFk": { - "type" : "number" + "type": "number" }, "educationLevelFk": { - "type" : "number" + "type": "number" }, "SSN": { - "type" : "string" + "type": "string" }, "mobileExtension": { - "type" : "number" + "type": "number" }, "code": { - "type" : "string" + "type": "string", + "required": true }, "fi": { - "type" : "string" + "type": "string" }, "birth": { - "type" : "date" + "type": "date" }, "isF11Allowed": { - "type" : "boolean" + "type": "boolean" }, "sex": { - "type" : "string" + "type": "string" }, "isFreelance": { - "type" : "boolean" + "type": "boolean" + }, + "fiDueDate": { + "type": "date" + }, + "hasMachineryAuthorized": { + "type": "boolean" + }, + "seniority": { + "type": "date" + }, + "isDisable": { + "type": "boolean" + }, + "isSsDiscounted": { + "type": "boolean" } }, "relations": { @@ -101,7 +117,7 @@ "foreignKey": "workerFk" } }, - "acls":[ + "acls": [ { "property": "__get__locker", "accessType": "READ", @@ -110,4 +126,4 @@ "principalId": "$owner" } ] -} +} \ No newline at end of file diff --git a/modules/worker/front/basic-data/index.html b/modules/worker/front/basic-data/index.html index aa3f6ca79..bece1b6fd 100644 --- a/modules/worker/front/basic-data/index.html +++ b/modules/worker/front/basic-data/index.html @@ -54,8 +54,8 @@ diff --git a/modules/worker/front/pda/index.html b/modules/worker/front/pda/index.html deleted file mode 100644 index c6d31dc85..000000000 --- a/modules/worker/front/pda/index.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - ID: {{id}} - - - {{modelFk}}, {{serialNumber}} - - - - - - - - - - diff --git a/modules/worker/front/pda/index.js b/modules/worker/front/pda/index.js index 885261e5c..c3616b41e 100644 --- a/modules/worker/front/pda/index.js +++ b/modules/worker/front/pda/index.js @@ -1,53 +1,18 @@ import ngModule from '../module'; import Section from 'salix/components/section'; -import './style.scss'; class Controller extends Section { constructor($element, $) { super($element, $); - const filter = { - where: {userFk: this.$params.id}, - include: {relation: 'deviceProduction'} - }; - this.$http.get('DeviceProductionUsers', {filter}). - then(res => { - if (res.data && res.data.length > 0) - this.setCurrentPDA(res.data[0]); - }); } - deallocatePDA() { - this.$http.post(`Workers/${this.$params.id}/deallocatePDA`, {pda: this.currentPDA.deviceProductionFk}) - .then(() => { - this.vnApp.showSuccess(this.$t('PDA deallocated')); - delete this.currentPDA; - }); - } - - allocatePDA() { - this.$http.post(`Workers/${this.$params.id}/allocatePDA`, {pda: this.newPDA}) - .then(res => { - if (res.data) - this.setCurrentPDA(res.data); - - this.vnApp.showSuccess(this.$t('PDA allocated')); - delete this.newPDA; - }); - } - - setCurrentPDA(data) { - this.currentPDA = data; - this.currentPDA.description = []; - this.currentPDA.description.push(`ID: ${this.currentPDA.deviceProductionFk}`); - this.currentPDA.description.push(`${this.$t('Model')}: ${this.currentPDA.deviceProduction.modelFk}`); - this.currentPDA.description.push(`${this.$t('Serial Number')}: ${this.currentPDA.deviceProduction.serialNumber}`); - this.currentPDA.description = this.currentPDA.description.join(' '); + async $onInit() { + const url = await this.vnApp.getUrl(`worker/${this.$params.id}/pda`); + this.$state.go('worker.card.summary', {id: this.$params.id}); + window.location.href = url; } } -Controller.$inject = ['$element', '$scope']; - ngModule.vnComponent('vnWorkerPda', { - template: require('./index.html'), - controller: Controller, + controller: Controller }); diff --git a/modules/worker/front/pda/index.spec.js b/modules/worker/front/pda/index.spec.js deleted file mode 100644 index a0540af45..000000000 --- a/modules/worker/front/pda/index.spec.js +++ /dev/null @@ -1,72 +0,0 @@ -import './index'; - -describe('Worker', () => { - describe('Component vnWorkerPda', () => { - let $httpBackend; - let $scope; - let $element; - let controller; - - beforeEach(ngModule('worker')); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - $element = angular.element(''); - controller = $componentController('vnWorkerPda', {$element, $scope}); - $httpBackend.expectGET(`DeviceProductionUsers`).respond(); - })); - - describe('deallocatePDA()', () => { - it('should make an HTTP Post query to deallocatePDA', () => { - jest.spyOn(controller.vnApp, 'showSuccess'); - controller.currentPDA = {deviceProductionFk: 1}; - controller.$params.id = 1; - - $httpBackend - .expectPOST(`Workers/${controller.$params.id}/deallocatePDA`, - {pda: controller.currentPDA.deviceProductionFk}) - .respond(); - controller.deallocatePDA(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalled(); - expect(controller.currentPDA).toBeUndefined(); - }); - }); - - describe('allocatePDA()', () => { - it('should make an HTTP Post query to allocatePDA', () => { - jest.spyOn(controller.vnApp, 'showSuccess'); - controller.newPDA = 4; - controller.$params.id = 1; - - $httpBackend - .expectPOST(`Workers/${controller.$params.id}/allocatePDA`, - {pda: controller.newPDA}) - .respond(); - controller.allocatePDA(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalled(); - expect(controller.newPDA).toBeUndefined(); - }); - }); - - describe('setCurrentPDA()', () => { - it('should set CurrentPDA', () => { - const data = { - deviceProductionFk: 1, - deviceProduction: { - modelFk: 1, - serialNumber: 1 - } - }; - controller.setCurrentPDA(data); - - expect(controller.currentPDA).toBeDefined(); - expect(controller.currentPDA.description).toBeDefined(); - }); - }); - }); -}); diff --git a/modules/worker/front/pda/style.scss b/modules/worker/front/pda/style.scss deleted file mode 100644 index c55c9d218..000000000 --- a/modules/worker/front/pda/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -@import "./variables"; - -.text-grey { - color: $color-font-light; -} - diff --git a/modules/zone/back/methods/zone/specs/deleteZone.spec.js b/modules/zone/back/methods/zone/specs/deleteZone.spec.js index 968685fec..08dafd181 100644 --- a/modules/zone/back/methods/zone/specs/deleteZone.spec.js +++ b/modules/zone/back/methods/zone/specs/deleteZone.spec.js @@ -5,6 +5,7 @@ describe('zone deletezone()', () => { const userId = 9; const activeCtx = { accessToken: {userId: userId}, + __: value => value }; const ctx = {req: activeCtx}; const zoneId = 9; @@ -15,19 +16,15 @@ describe('zone deletezone()', () => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: activeCtx }); - try { - const originalTickets = await models.Ticket.find({ - where: { - zoneFk: zoneId - } - }); - ticketIDs = originalTickets.map(ticket => ticket.id); - originalTicketStates = await models.TicketState.find({where: { - ticketFk: {inq: ticketIDs}, - code: 'FIXING'}}); - } catch (error) { - console.error(error); - } + const originalTickets = await models.Ticket.find({ + where: { + zoneFk: zoneId + } + }); + ticketIDs = originalTickets.map(ticket => ticket.id); + originalTicketStates = await models.TicketState.find({where: { + ticketFk: {inq: ticketIDs}, + code: 'FIXING'}}); }); it('should delete a zone and update their tickets', async() => { diff --git a/myt.config.yml b/myt.config.yml index 17300aa37..56239ca3c 100755 --- a/myt.config.yml +++ b/myt.config.yml @@ -227,7 +227,7 @@ localFixtures: - expeditionScan - expeditionState - expeditionStateType - - expeditionTruck + - roadmapStop - expense - genus - greuge diff --git a/package.json b/package.json index 390b61be1..8b8281e0d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.22.0", + "version": "24.26.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", diff --git a/print/templates/reports/collection-label/sql/labelsData.sql b/print/templates/reports/collection-label/sql/labelsData.sql index 2ffa6d8db..c96817b9c 100644 --- a/print/templates/reports/collection-label/sql/labelsData.sql +++ b/print/templates/reports/collection-label/sql/labelsData.sql @@ -35,7 +35,7 @@ SELECT c.itemPackingTypeFk code, LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id JOIN vn.productionConfig pc WHERE t.id IN (?) diff --git a/print/templates/reports/expedition-pallet-label/sql/labelData.sql b/print/templates/reports/expedition-pallet-label/sql/labelData.sql index 385614305..49a4031ae 100644 --- a/print/templates/reports/expedition-pallet-label/sql/labelData.sql +++ b/print/templates/reports/expedition-pallet-label/sql/labelData.sql @@ -5,7 +5,7 @@ SELECT ep.id palletFk, COUNT(es.id) labels, t.warehouseFk warehouseFk, dayname(r.created) `dayName`, - rs.id <=> rm.expeditionTruckFk isMatch + rs.id <=> rm.roadmapStopFk isMatch FROM vn.roadmapStop rs JOIN vn.expeditionPallet ep ON ep.truckFk = rs.id JOIN vn.expeditionScan es ON es.palletFk = ep.id @@ -13,7 +13,7 @@ SELECT ep.id palletFk, JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs2 ON rs2.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs2 ON rs2.id = rm.roadmapStopFk WHERE ep.id = ? GROUP BY ep.id, t.routeFk ORDER BY t.routeFk